Skip to content

Commit

Permalink
feat: add HidePartialKeys option
Browse files Browse the repository at this point in the history
  • Loading branch information
tim-ywliu committed Oct 13, 2022
1 parent d45de03 commit 54fe8cd
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ type Formatter struct {
// HideKeys - show [fieldValue] instead of [fieldKey:fieldValue]
HideKeys bool

// HidePartialKeys - show [fieldValue] instead of [fieldKey:fieldValue] if fieldKey in the map
// HidePartialKeys will have a lower priority than HideKeys.
HidePartialKeys map[string]bool

// NoColors - disable colors
NoColors bool

Expand Down
6 changes: 5 additions & 1 deletion formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ type Formatter struct {
// HideKeys - show [fieldValue] instead of [fieldKey:fieldValue]
HideKeys bool

// HidePartialKeys - show [fieldValue] instead of [fieldKey:fieldValue] if fieldKey in the map
// HidePartialKeys will have a lower priority than HideKeys.
HidePartialKeys map[string]bool

// NoColors - disable colors
NoColors bool

Expand Down Expand Up @@ -184,7 +188,7 @@ func (f *Formatter) writeOrderedFields(b *bytes.Buffer, entry *logrus.Entry) {
}

func (f *Formatter) writeField(b *bytes.Buffer, entry *logrus.Entry, field string) {
if f.HideKeys {
if f.HideKeys || (f.HidePartialKeys != nil && f.HidePartialKeys[field]) {
fmt.Fprintf(b, "[%v]", entry.Data[field])
} else {
fmt.Fprintf(b, "[%s:%v]", field, entry.Data[field])
Expand Down
28 changes: 28 additions & 0 deletions tests/formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ func ExampleFormatter_Format_full_level() {
// - [WARNING] test3
// - [ERROR] test4
}

func ExampleFormatter_Format_show_keys() {
l := logrus.New()
l.SetOutput(os.Stdout)
Expand Down Expand Up @@ -96,6 +97,33 @@ func ExampleFormatter_Format_hide_keys() {
// - [INFO] [rest] test2
}

func ExampleFormatter_Format_hide_partial_keys() {
l := logrus.New()
l.SetOutput(os.Stdout)
l.SetLevel(logrus.DebugLevel)
l.SetFormatter(&formatter.Formatter{
NoColors: true,
TimestampFormat: "-",
FieldsOrder: []string{"component", "category"},
HideKeys: false,
HidePartialKeys: map[string]bool{
"component": true,
},
})

ll := l.WithField("component", "main")
lll := ll.WithField("category", "rest")

l.Info("test1")
ll.Info("test2")
lll.Info("test3")

// Output:
// - [INFO] test1
// - [INFO] [main] test2
// - [INFO] [main] [category:rest] test3
}

func ExampleFormatter_Format_sort_order() {
l := logrus.New()
l.SetOutput(os.Stdout)
Expand Down

0 comments on commit 54fe8cd

Please sign in to comment.