accessLog 记录每次 HTTP 请求的方法、路径、状态码和耗时。 5xx 响应额外打印响应体,方便排查服务端错误。
(next http.Handler)
| 1279 | // accessLog 记录每次 HTTP 请求的方法、路径、状态码和耗时。 |
| 1280 | // 5xx 响应额外打印响应体,方便排查服务端错误。 |
| 1281 | func accessLog(next http.Handler) http.Handler { |
| 1282 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 1283 | rw := &statusWriter{ResponseWriter: w, status: http.StatusOK} |
| 1284 | start := time.Now() |
| 1285 | next.ServeHTTP(rw, r) |
| 1286 | elapsed := time.Since(start).Round(time.Millisecond) |
| 1287 | if rw.status >= 500 && rw.body.Len() > 0 { |
| 1288 | log.Printf("%s %s %d %s body=%s", r.Method, r.URL.Path, rw.status, elapsed, rw.body.String()) |
| 1289 | } else { |
| 1290 | log.Printf("%s %s %d %s", r.Method, r.URL.Path, rw.status, elapsed) |
| 1291 | } |
| 1292 | }) |
| 1293 | } |
| 1294 | |
| 1295 | type statusWriter struct { |
| 1296 | http.ResponseWriter |