refactor: 后端日志系统重构
- 新增模块化日志器(pkg/logger/module.go) - 新增 GORM 日志适配器 - 统一日志入口,移除所有 zap.L() 全局 logger 调用 - 字段标准化 - 启动阶段使用结构化日志 - 更新所有相关测试
This commit is contained in:
@@ -1,13 +1,20 @@
|
||||
package logger
|
||||
|
||||
import "go.uber.org/zap"
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
const requestIDKey = "request_id"
|
||||
|
||||
// WithRequestID 向 logger 添加 request_id 字段
|
||||
func WithRequestID(logger *zap.Logger, requestID string) *zap.Logger {
|
||||
return logger.With(zap.String("request_id", requestID))
|
||||
return logger.With(zap.String(requestIDKey, requestID))
|
||||
}
|
||||
|
||||
// WithContext 向 logger 添加多个自定义字段
|
||||
func WithContext(logger *zap.Logger, fields map[string]interface{}) *zap.Logger {
|
||||
zapFields := make([]zap.Field, 0, len(fields))
|
||||
for k, v := range fields {
|
||||
@@ -15,3 +22,37 @@ func WithContext(logger *zap.Logger, fields map[string]interface{}) *zap.Logger
|
||||
}
|
||||
return logger.With(zapFields...)
|
||||
}
|
||||
|
||||
func RequestIDFromGinContext(c *gin.Context) zap.Field {
|
||||
requestID, exists := c.Get("request_id")
|
||||
if !exists {
|
||||
return zap.Skip()
|
||||
}
|
||||
if id, ok := requestID.(string); ok {
|
||||
return RequestID(id)
|
||||
}
|
||||
return zap.Skip()
|
||||
}
|
||||
|
||||
func RequestIDFromContext(ctx context.Context) zap.Field {
|
||||
requestID := ctx.Value(ctxKey{})
|
||||
if requestID == nil {
|
||||
return zap.Skip()
|
||||
}
|
||||
if id, ok := requestID.(string); ok {
|
||||
return RequestID(id)
|
||||
}
|
||||
return zap.Skip()
|
||||
}
|
||||
|
||||
func ContextWithRequestID(ctx context.Context, requestID string) context.Context {
|
||||
return context.WithValue(ctx, ctxKey{}, requestID)
|
||||
}
|
||||
|
||||
func LoggerFromContext(ctx context.Context, baseLogger *zap.Logger) *zap.Logger {
|
||||
field := RequestIDFromContext(ctx)
|
||||
if field == zap.Skip() {
|
||||
return baseLogger
|
||||
}
|
||||
return baseLogger.With(field)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user