Skip to content

Commit

Permalink
Change log format to integrate with GCP
Browse files Browse the repository at this point in the history
  • Loading branch information
st-matskevich committed Nov 5, 2023
1 parent 74f13db commit 6c7bc11
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
3 changes: 2 additions & 1 deletion api/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"log/slog"

"github.com/gofiber/fiber/v2"
slogfiber "github.com/samber/slog-fiber"
)

type Controller interface {
Expand Down Expand Up @@ -31,6 +32,6 @@ func HandlerPrintf(c *fiber.Ctx, severity int, message string, v ...any) {
logger = slog.Error
}

args := append([]any{"method", c.Method(), "path", c.Path(), "request-id", c.Context().UserValue("request-id")}, v...)
args := append([]any{"request-id", slogfiber.GetRequestID(c)}, v...)
logger(message, args...)
}
16 changes: 15 additions & 1 deletion api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,21 @@ import (
)

func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
// Replace keys to allow GCP to parse logs correctly
// https://cloud.google.com/logging/docs/structured-logging
opts := slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
switch a.Key {
case "level":
a.Key = "severity"
case "msg":
a.Key = "message"
}
return a
},
}

logger := slog.New(slog.NewJSONHandler(os.Stdout, &opts))
slog.SetDefault(logger)

slog.Info("Starting API service")
Expand Down

0 comments on commit 6c7bc11

Please sign in to comment.