Skip to content

Commit

Permalink
props in json format
Browse files Browse the repository at this point in the history
  • Loading branch information
leodeim committed Dec 8, 2023
1 parent eb0cdb5 commit c5a8ad1
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
5 changes: 5 additions & 0 deletions examples/examples.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
1 change: 1 addition & 0 deletions examples/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ var examples = []func(){
simpleTextLogger,
nonBlocking,
propsLogger,
propsJsonLogger,
}

func main() {
Expand Down
23 changes: 17 additions & 6 deletions formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit c5a8ad1

Please sign in to comment.