Skip to content

Commit

Permalink
enhancement: add structured logging to output
Browse files Browse the repository at this point in the history
  • Loading branch information
goenning committed Jun 20, 2021
1 parent b342db6 commit 8da8785
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
3 changes: 2 additions & 1 deletion app/pkg/env/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ type config struct {
Host string `env:"CDN_HOST"`
}
Log struct {
Level string `env:"LOG_LEVEL,default=INFO"`
Level string `env:"LOG_LEVEL,default=INFO"`
Structured bool `env:"LOG_STRUCTURED,default=false"`
}
OAuth struct {
Google struct {
Expand Down
20 changes: 11 additions & 9 deletions app/services/log/console/console.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package console

import (
"context"
"encoding/json"
stdLog "log"
"os"
"time"
Expand Down Expand Up @@ -69,18 +70,19 @@ func writeLog(ctx context.Context, level log.Level, message string, props dto.Pr
}

props = log.GetProperties(ctx).Merge(props)
message = log.Parse(message, props, true)
tag := props[log.PropertyKeyTag]
if tag == nil {
tag = "???"
props["Level"] = level.String()
props["Message"] = log.Parse(message, props, !env.Config.Log.Structured)
props["Timestamp"] = time.Now().Format(time.RFC3339)
if props[log.PropertyKeyTag] == nil {
props[log.PropertyKeyTag] = "???"
}

contextID := props[log.PropertyKeyContextID]
if contextID == nil {
stdOut.Printf("%s [%s] [%s] %s\n", colorizeLevel(level), time.Now().Format(time.RFC3339), tag, message)
} else {
stdOut.Printf("%s [%s] [%s] [%s] %s\n", colorizeLevel(level), time.Now().Format(time.RFC3339), tag, contextID, message)
if env.Config.Log.Structured {
_ = json.NewEncoder(stdOut.Writer()).Encode(props)
return
}

stdOut.Printf("%s [%s] [%s] %s\n", colorizeLevel(level), props["Timestamp"], props[log.PropertyKeyTag], props["Message"])
}

func colorizeLevel(level log.Level) string {
Expand Down

0 comments on commit 8da8785

Please sign in to comment.