From 1d7177fb26596e412439f9163dc15de0335c8de3 Mon Sep 17 00:00:00 2001 From: Martin Riedl Date: Wed, 5 Mar 2025 17:48:47 +0100 Subject: [PATCH] feat: new priority key settings for key value formatter --- cmd/keyValueFormatter/main.go | 30 ++++++++++++++++++++++++++++++ formatter_keyvalue.go | 26 ++++++++++++++++++++++++-- 2 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 cmd/keyValueFormatter/main.go diff --git a/cmd/keyValueFormatter/main.go b/cmd/keyValueFormatter/main.go new file mode 100644 index 0000000..9e1424a --- /dev/null +++ b/cmd/keyValueFormatter/main.go @@ -0,0 +1,30 @@ +package main + +import ( + "time" + + "git.martin-riedl.de/golang/log" +) + +func main() { + advancedSettings() +} + +func advancedSettings() { + // Key Value Formatter with special settings + formatter := log.NewFormatterKeyValue() + formatter.HighPriorityKeys = []string{"firstField"} + formatter.PriorityKeys = []string{"secondField"} + formatter.TimeFormat = time.RFC3339Nano + + // create new log instance + output := log.NewOutput(log.LevelDebug, formatter, log.NewPrinterStdout()) + logger := log.NewLogger([]*log.Output{output}) + + // log some message + logger.WithMap(log.Map{ + "someField": "Martin", + "firstField": "John", + "secondField": "Doe", + }).Info("This is an info message") +} diff --git a/formatter_keyvalue.go b/formatter_keyvalue.go index e8da5d2..74ac8ab 100644 --- a/formatter_keyvalue.go +++ b/formatter_keyvalue.go @@ -16,12 +16,17 @@ package log import ( "fmt" + "slices" "strings" "time" ) type FormatterKeyValue struct { - TimeFormat string + TimeFormat string + // HighPriorityKeys are printed before the actual log message + HighPriorityKeys []string + // PriorityKeys are printed after the log message + PriorityKeys []string builder strings.Builder isFirstKVWritten bool } @@ -45,9 +50,23 @@ func (formatter *FormatterKeyValue) Begin(entry *Entry) { } func (formatter *FormatterKeyValue) Process(entry *Entry) { + // log high priority keys + for _, content := range entry.Content { + if slices.Contains(formatter.HighPriorityKeys, content.Key) { + formatter.addKV(content.Key, content.Value) + } + } + // add message formatter.addKV("message", entry.Message) + // log priority keys + for _, content := range entry.Content { + if slices.Contains(formatter.PriorityKeys, content.Key) { + formatter.addKV(content.Key, content.Value) + } + } + // add call stack if len(entry.CallStack) > 0 { caller := entry.CallStack[0] @@ -57,7 +76,10 @@ func (formatter *FormatterKeyValue) Process(entry *Entry) { // add additional fields for _, content := range entry.Content { - formatter.addKV(content.Key, content.Value) + if !slices.Contains(formatter.HighPriorityKeys, content.Key) && + !slices.Contains(formatter.PriorityKeys, content.Key) { + formatter.addKV(content.Key, content.Value) + } } }