使用指南
HTTP 请求日志
用标准 HTTP 中间件记录请求,定制状态级别、请求 ID 和跳过规则。
包装 HTTP 路由
用 HTTPMiddleware 包装标准库的 http.Handler,每个未跳过的请求在处理后记录一次。零值的 HTTPConfig 可直接使用,记录包含方法、路径和响应状态等字段。
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: stable}))
handler := sl.HTTPMiddleware(logger, sl.HTTPConfig{})(http.NotFoundHandler())
handler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/missing", nil))level=WARN msg="http request" request.method=GET request.path=/missing request.query="" request.ip=192.0.2.1:1234 request.user_agent="" response.status=404 response.bytes=19按请求调整记录
示例通过 HTTPConfig.RequestIDHeader 记录指定请求头,用 HTTPConfig.Skip 跳过健康检查。它把 404 映射为 Debug,其余状态交给 StatusLevel。默认映射中,2xx 和 3xx 为 Info,4xx 为 Warn,5xx 为 Error。
// The zero HTTPConfig works as is. This one also logs the request ID,
// logs 404s at Debug, and skips the health check.
handler := sl.HTTPMiddleware(logger, sl.HTTPConfig{
RequestIDHeader: "X-Request-Id",
Level: func(status int) slog.Level {
if status == http.StatusNotFound {
return slog.LevelDebug
}
return sl.StatusLevel(status) // the default: 2xx/3xx Info, 4xx Warn, 5xx Error
},
Skip: func(r *http.Request) bool { return r.URL.Path == "/healthz" },
})(mux)
// In a real server: http.ListenAndServe(":8080", handler)