- 配置 slog JSON 输出和日志级别 - 添加请求 ID、访问日志及上下文日志工具 - 拆分启动初始化并统一启动失败处理 BREAKING CHANGE: 配置文件必须提供 log.level,缺失或非法将导致启动失败
31 lines
552 B
Go
31 lines
552 B
Go
package middleware
|
|
|
|
import (
|
|
"lyra/internal/util"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func AccessLogMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
start := time.Now()
|
|
|
|
c.Next()
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
util.Logger(ctx).InfoContext(
|
|
ctx,
|
|
"http request",
|
|
"method", c.Request.Method,
|
|
"path", c.Request.URL.Path,
|
|
"status", c.Writer.Status(),
|
|
"latency_ms", time.Since(start).Milliseconds(),
|
|
"client_ip", c.ClientIP(),
|
|
"user_agent", c.Request.UserAgent(),
|
|
"response_size", c.Writer.Size(),
|
|
)
|
|
}
|
|
}
|