Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add context to http server log middleware #500

Merged
merged 1 commit into from
Nov 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
Loading