From c5a8ad1b1efba4d70d2a5c19a13c9a6d3fef55bd Mon Sep 17 00:00:00 2001 From: Leonidas Date: Fri, 8 Dec 2023 16:22:16 +0200 Subject: [PATCH] props in json format --- examples/examples.go | 5 +++++ examples/main.go | 1 + formatter.go | 23 +++++++++++++++++------ 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/examples/examples.go b/examples/examples.go index a0d834d..0cdd9bb 100644 --- a/examples/examples.go +++ b/examples/examples.go @@ -68,3 +68,8 @@ func propsLogger() { l := log.New(log.WithName("props"), log.WithWriter(os.Stdout, log.FormatTextColor)) l.Warning().Prop("prop1", "hello").Prop("prop2", "world").Msg("I can log in simple text format") } + +func propsJsonLogger() { + l := log.New(log.WithName("propsJson"), log.WithWriter(os.Stdout, log.FormatJson)) + l.Warning().Prop("prop1", "hello").Prop("prop2", "world").Msg("I can log in simple json format") +} diff --git a/examples/main.go b/examples/main.go index 093521d..2c4666c 100644 --- a/examples/main.go +++ b/examples/main.go @@ -14,6 +14,7 @@ var examples = []func(){ simpleTextLogger, nonBlocking, propsLogger, + propsJsonLogger, } func main() { diff --git a/formatter.go b/formatter.go index b258b8e..37808e6 100644 --- a/formatter.go +++ b/formatter.go @@ -131,15 +131,26 @@ func levelToColor(level Level) string { } } +type JsonStruct struct { + Time string `json:"time"` + Level string `json:"level"` + Module string `json:"module"` + Message string `json:"message"` + Props map[string]string `json:"props"` +} + func (_formatter) json(props *formatterProps) (string, error) { logger := props.message.super - b, err := json.Marshal(map[string]string{ - "time": time.Now().Format(logger.global.dateFormat), - "level": string(props.message.level), - "module": logger.local.name, - "message": props.message.text, - }) + j := JsonStruct{ + Time: time.Now().Format(logger.global.dateFormat), + Level: string(props.message.level), + Module: logger.local.name, + Message: props.message.text, + Props: props.message.props, + } + + b, err := json.Marshal(j) if err != nil { return "", fmt.Errorf("error while formatting log message: %v", err)