Skip to content

Commit

Permalink
Merge pull request #1 from interline-io/ctx-log
Browse files Browse the repository at this point in the history
Ctx log
  • Loading branch information
irees authored Jan 25, 2024
2 parents c768586 + b5cbf20 commit e943425
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 8 deletions.
15 changes: 15 additions & 0 deletions ctx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package log

import (
"context"

"github.com/rs/zerolog"
)

func For(ctx context.Context) *zerolog.Logger {
return zerolog.Ctx(ctx)
}

func WithLogger(ctx context.Context, logger zerolog.Logger) context.Context {
return logger.WithContext(ctx)
}
24 changes: 16 additions & 8 deletions lmw.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,32 +13,40 @@ import (
func LoggingMiddleware(longQueryDuration int, getUserName func(context.Context) string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
t1 := time.Now()
// Setup context logger
// Add username
rlog := Logger.With()
if getUserName != nil {
if u := getUserName(r.Context()); u != "" {
rlog = rlog.Str("user", getUserName(r.Context()))
}
}
// Add request ID
// TODO
rlogger := rlog.Logger()
r = r.WithContext(WithLogger(r.Context(), rlogger))

// Get request body for logging if request is json and length under 20kb
t1 := time.Now()
var body []byte
if r.Header.Get("content-type") == "application/json" && r.ContentLength < 1024*20 {
body, _ = io.ReadAll(r.Body)
r.Body = io.NopCloser(bytes.NewBuffer(body))
}

// Wrap context to get error code and errors
wr := wrapResponseWriter(w)
next.ServeHTTP(wr, r)

// Extra logging of request body if duration > 1s
durationMs := (time.Now().UnixNano() - t1.UnixNano()) / 1e6
msg := Info().
msg := rlogger.Info().
Int64("duration_ms", durationMs).
Str("method", r.Method).
Str("path", r.URL.EscapedPath()).
Str("query", r.URL.Query().Encode()).
Int("status", wr.status)

// Add username
if getUserName != nil {
msg = msg.Str("user", getUserName(ctx))
}

// Add duration info
if durationMs > int64(longQueryDuration) {
// Verify it's valid json
Expand Down
1 change: 1 addition & 0 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,5 @@ func init() {
if v := os.Getenv("TL_LOG"); v != "" {
setLevelByName(v)
}
zerolog.DefaultContextLogger = &Logger
}

0 comments on commit e943425

Please sign in to comment.