Skip to content

Commit

Permalink
Add context to http server log middleware (#500)
Browse files Browse the repository at this point in the history
  • Loading branch information
Crevil committed Nov 12, 2023
1 parent 96e2ef7 commit d63510b
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 5 deletions.
7 changes: 2 additions & 5 deletions cmd/server/http/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,13 @@ func reqrespLogger(h http.Handler) http.Handler {
// request duration in miliseconds
duration := time.Since(start).Nanoseconds() / 1e6
statusCode := statusWriter.statusCode
requestID := getRequestID(r)
fields := []interface{}{
"requestId", requestID,
"req", struct {
ID string `json:"id,omitempty"`
URL string `json:"url,omitempty"`
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
}{
ID: requestID,
URL: r.URL.RequestURI(),
Method: r.Method,
Path: r.URL.Path,
Expand All @@ -58,7 +54,8 @@ func reqrespLogger(h http.Handler) http.Handler {
if err != nil {
fields = append(fields, "error", err)
}
logger := log.With(fields...)

logger := log.WithContext(r.Context()).With(fields...)
if statusCode >= http.StatusInternalServerError {
logger.Errorf("[%d] %s %s", statusCode, r.Method, r.URL.Path)
return
Expand Down
4 changes: 4 additions & 0 deletions internal/log/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,9 @@ func WithContext(ctx context.Context) *Logger {

// AddContext adds fields to the context that can be used in WithContext.
func AddContext(ctx context.Context, fields ...interface{}) context.Context {
values, ok := ctx.Value(contextKey{}).([]interface{})
if ok && values != nil {
fields = append(fields, values...)
}
return context.WithValue(ctx, contextKey{}, fields)
}

0 comments on commit d63510b

Please sign in to comment.