69 lines
1.9 KiB
Go
69 lines
1.9 KiB
Go
package middleware
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
// TraceIDHeader 贯穿链路的追踪头(上游已有则透传,否则生成)。
|
|
const TraceIDHeader = "X-Trace-Id"
|
|
|
|
// TraceIDKey gin.Context 中 trace_id 的键。
|
|
const TraceIDKey = "trace_id"
|
|
|
|
// Logger Gin 请求日志中间件(Day 5):
|
|
// 每个请求记录一条结构化日志,字段含 trace_id / status / method / path /
|
|
// client_ip / latency / body_size / user_agent,并以 X-Trace-Id 响应头回传。
|
|
func Logger(lg *zap.Logger) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
start := time.Now()
|
|
|
|
traceID := c.GetHeader(TraceIDHeader)
|
|
if traceID == "" {
|
|
traceID = NewTraceID()
|
|
}
|
|
c.Set(TraceIDKey, traceID)
|
|
c.Header(TraceIDHeader, traceID)
|
|
|
|
c.Next()
|
|
|
|
fields := []zap.Field{
|
|
zap.String("trace_id", traceID),
|
|
zap.Int("status", c.Writer.Status()),
|
|
zap.String("method", c.Request.Method),
|
|
zap.String("path", c.Request.URL.Path),
|
|
zap.String("client_ip", c.ClientIP()),
|
|
zap.Duration("latency", time.Since(start)),
|
|
zap.Int("body_size", c.Writer.Size()),
|
|
zap.String("user_agent", c.Request.UserAgent()),
|
|
}
|
|
if len(c.Errors) > 0 {
|
|
fields = append(fields, zap.String("errors", c.Errors.String()))
|
|
}
|
|
|
|
switch {
|
|
case c.Writer.Status() >= 500:
|
|
lg.Error("http_request", fields...)
|
|
case c.Writer.Status() >= 400:
|
|
lg.Warn("http_request", fields...)
|
|
default:
|
|
lg.Info("http_request", fields...)
|
|
}
|
|
}
|
|
}
|
|
|
|
// NewTraceID 生成 16 字符 hex 追踪 ID(时间戳前缀 + 随机数,便于肉眼按时间排序)。
|
|
// Day 8 雪花 ID 落地后可替换为全局 ID 生成器。
|
|
func NewTraceID() string {
|
|
var b [8]byte
|
|
if _, err := rand.Read(b[:]); err != nil {
|
|
// crypto/rand 失败极罕见,退化为纳秒时间戳
|
|
return hex.EncodeToString([]byte(time.Now().Format("150405.000000000")))
|
|
}
|
|
return hex.EncodeToString(b[:])
|
|
}
|