通过中间件拦截请求并包装ResponseWriter,可记录方法、路径、IP、状态码和耗时。1. 定义LoggingMiddleware捕获请求前后信息;2. 自定义responseWriter获取状态码;3. 集成到mux路由;4. 可选slog输出结构化日志。

在Go语言项目中实现请求日志收集,核心是通过中间件机制拦截HTTP请求,记录关键信息如请求路径、方法、耗时、客户端IP、响应状态码等。以下是一个结构清晰、实用的实现方式。
Go的net/http包支持中间件模式,可以在处理请求前后插入日志逻辑。
定义一个日志中间件函数,包装原有的http.Handler:
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// 记录客户端IP
clientIP := r.RemoteAddr
if ip := r.Header.Get("X-Real-IP"); ip != "" {
clientIP = ip
} else if ip = r.Header.Get("X-Forwarded-For"); ip != "" {
clientIP = strings.Split(ip, ",")[0]
}
// 包装ResponseWriter以捕获状态码
rw := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
// 调用下一个处理器
next.ServeHTTP(rw, r)
// 日志输出
log.Printf(
"%s %s %s %d %v",
r.Method,
r.URL.Path,
clientIP,
rw.statusCode,
time.Since(start),
)
})
}原生http.ResponseWriter不提供获取状态码的方法,需自定义包装类型:
立即学习“go语言免费学习笔记(深入)”;
type responseWriter struct {
http.ResponseWriter
statusCode int
}
func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}这样就能在中间件中准确记录实际返回的状态码,即使发生内部错误也能捕获。
将日志中间件应用到路由上:
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
// 使用中间件包裹处理器
loggedMux := LoggingMiddleware(mux)
log.Println("Server starting on :8080")
http.ListenAndServe(":8080", loggedMux)
}每次请求都会输出类似日志:
GET / 127.0.0.1:54321 200 123.456µs
可结合log/slog(Go 1.21+)输出JSON格式日志,便于收集分析:
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Info("request",
"method", r.Method,
"path", r.URL.Path,
"ip", clientIP,
"status", rw.statusCode,
"duration_ms", time.Since(start).Milliseconds(),
)也可将日志写入文件或发送到ELK、Loki等日志系统。
基本上就这些。通过中间件加ResponseWriter包装,能干净地实现完整的请求日志收集,不影响业务逻辑,也易于扩展。
以上就是Golang如何实现请求日志收集的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号