Skip to content

Commit

Permalink
gomods#1890 modifying logger pkg to use slog
Browse files Browse the repository at this point in the history
  • Loading branch information
Madhur committed Dec 4, 2024
1 parent bd63c16 commit 647228e
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 7 deletions.
18 changes: 15 additions & 3 deletions pkg/log/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,21 @@ import (
)

func getGCPFormatter(level slog.Level) *slog.Logger {

l := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level}))
return l
return slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: level,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
switch a.Key {
case slog.LevelKey:
return slog.String("severity", a.Value.String())
case slog.MessageKey:
return slog.String("message", a.Value.String())
case slog.TimeKey:
return slog.String("timestamp", a.Value.Time().Format(time.RFC3339))
default:
return a
}
},
}))
}

const lightGrey = 0xffccc
Expand Down
3 changes: 1 addition & 2 deletions pkg/middleware/log_entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"github.com/gomods/athens/pkg/log"
"github.com/gomods/athens/pkg/requestid"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
)

// LogEntryMiddleware builds a log.Entry, setting the request fields
Expand All @@ -15,7 +14,7 @@ func LogEntryMiddleware(lggr *log.Logger) mux.MiddlewareFunc {
return func(h http.Handler) http.Handler {
f := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ent := lggr.WithFields(logrus.Fields{
ent := lggr.WithFields(map[string]interface{}{
"http-method": r.Method,
"http-path": r.URL.Path,
"request-id": requestid.FromContext(ctx),
Expand Down
4 changes: 2 additions & 2 deletions pkg/middleware/log_entry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ func TestLogContext(t *testing.T) {
r := mux.NewRouter()
r.HandleFunc("/test", h)

var buf bytes.Buffer
buf := &bytes.Buffer{}
lggr := log.New("", slog.LevelDebug, "")
opts := slog.HandlerOptions{Level: slog.LevelDebug}
handler := slog.NewJSONHandler(&buf, &opts)
handler := slog.NewJSONHandler(buf, &opts)
lggr.Logger = slog.New(handler)

r.Use(LogEntryMiddleware(lggr))
Expand Down

0 comments on commit 647228e

Please sign in to comment.