MCPcopy Index your code
hub / github.com/coder/coder / Logger

Function Logger

coderd/httpmw/loggermw/logger.go:71–129  ·  view source on GitHub ↗
(log slog.Logger, hostResolver func(*http.Request) string)

Source from the content-addressed store, hash-verified

69}
70
71func 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 }

Callers 12

NewFunction · 0.92
RouterMethod · 0.92
NewFunction · 0.92
apiHandlerMethod · 0.92
TestMiddlewareAccessLogFunction · 0.92

Calls 10

WithFieldsMethod · 0.95
WriteLogMethod · 0.95
safeQueryParamsFunction · 0.85
WithRequestLoggerFunction · 0.85
WithContextMethod · 0.80
ResponseBodyMethod · 0.80
NewRequestLoggerFunction · 0.70
GetMethod · 0.65
ContextMethod · 0.65
ServeHTTPMethod · 0.45