From 54fe8cd7bcbf4f96abbcc9c1b2200fc195e57e7f Mon Sep 17 00:00:00 2001 From: Tim Liu Date: Thu, 13 Oct 2022 05:23:08 +0000 Subject: [PATCH] feat: add HidePartialKeys option --- README.md | 4 ++++ formatter.go | 6 +++++- tests/formatter_test.go | 28 ++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 79317ef..ec7ba14 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/formatter.go b/formatter.go index 4034b69..ee94854 100644 --- a/formatter.go +++ b/formatter.go @@ -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 @@ -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]) diff --git a/tests/formatter_test.go b/tests/formatter_test.go index 6c0286b..a1fb4af 100644 --- a/tests/formatter_test.go +++ b/tests/formatter_test.go @@ -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) @@ -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)