| 69 | } |
| 70 | |
| 71 | func Logger(log slog.Logger, hostResolver func(*http.Request) string) func(next http.Handler) http.Handler { |
| 72 | return func(next http.Handler) http.Handler { |
| 73 | return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { |
| 74 | start := time.Now() |
| 75 | |
| 76 | sw, ok := rw.(*tracing.StatusWriter) |
| 77 | if !ok { |
| 78 | panic(fmt.Sprintf("ResponseWriter not a *tracing.StatusWriter; got %T", rw)) |
| 79 | } |
| 80 | |
| 81 | host := r.Host |
| 82 | if hostResolver != nil { |
| 83 | host = hostResolver(r) |
| 84 | } |
| 85 | |
| 86 | httplog := log.With( |
| 87 | slog.F("user_agent", r.Header.Get("User-Agent")), |
| 88 | slog.F("host", host), |
| 89 | slog.F("received_host", r.Host), |
| 90 | slog.F("path", r.URL.Path), |
| 91 | slog.F("proto", r.Proto), |
| 92 | slog.F("remote_addr", r.RemoteAddr), |
| 93 | // Include the start timestamp in the log so that we have the |
| 94 | // source of truth. There is at least a theoretical chance that |
| 95 | // there can be a delay between `next.ServeHTTP` ending and us |
| 96 | // actually logging the request. This can also be useful when |
| 97 | // filtering logs that started at a certain time (compared to |
| 98 | // trying to compute the value). |
| 99 | slog.F("start", start), |
| 100 | ) |
| 101 | |
| 102 | // Add safe query parameters to the log |
| 103 | if queryFields := safeQueryParams(r.URL.Query()); len(queryFields) > 0 { |
| 104 | httplog = httplog.With(queryFields...) |
| 105 | } |
| 106 | |
| 107 | logContext := NewRequestLogger(httplog, r.Method, start) |
| 108 | |
| 109 | ctx := WithRequestLogger(r.Context(), logContext) |
| 110 | |
| 111 | next.ServeHTTP(sw, r.WithContext(ctx)) |
| 112 | |
| 113 | // Don't log successful health check requests. |
| 114 | if r.URL.Path == "/api/v2" && sw.Status == http.StatusOK { |
| 115 | return |
| 116 | } |
| 117 | |
| 118 | // For status codes 500 and higher we |
| 119 | // want to log the response body. |
| 120 | if sw.Status >= http.StatusInternalServerError { |
| 121 | logContext.WithFields( |
| 122 | slog.F("response_body", string(sw.ResponseBody())), |
| 123 | ) |
| 124 | } |
| 125 | |
| 126 | logContext.WriteLog(r.Context(), sw.Status) |
| 127 | }) |
| 128 | } |