Documentation
¶
Overview ¶
Package logger 提供请求范围的日志工具
该包提供了一套完整的日志解决方案,包括: - RequestLogger: 请求范围的日志记录器,支持通过 context 传递 - 标准字段定义: 统一的日志字段命名规范 - GORM 日志适配器: 将 GORM 日志输出到结构化日志系统 - Redis 日志钩子: 记录 Redis 命令执行情况 - HTTP 日志中间件: Gin 框架的请求日志中间件 - gRPC 日志拦截器: gRPC 服务端日志拦截器
设计目标: 1. 上下文传递: 通过 context.Context 传递 Logger,确保追踪信息不丢失 2. 结构化日志: 所有日志必须是 key-value 结构,便于机器解析 3. 字段标准化: 统一字段命名,提供常量定义 4. 分层日志: 不同层级(HTTP/gRPC/Service/DB)有明确的日志策略 5. 零侵入性: 业务代码只需调用 logger.L(ctx),无需关心底层实现
基本用法:
func (s *userService) CreateUser(ctx context.Context, dto CreateUserDTO) (*User, error) {
l := logger.L(ctx)
l.Infow("开始创建用户",
"action", logger.ActionCreate,
"resource", logger.ResourceUser,
)
// ...
}
该包设计为可独立使用,未来可迁移到 component-base 供多个项目共享。
Index ¶
- Constants
- func ErrorFields(err error, code int) []log.Field
- func EventField(event string) log.Field
- func GRPCFields(method, service, code string) []log.Field
- func HTTPFields(method, path, query string, statusCode int) []log.Field
- func HTTPLogger() gin.HandlerFunc
- func HTTPLoggerWithConfig(config HTTPLoggerConfig) gin.HandlerFunc
- func NewGormLogger(level int) gormlogger.Interface
- func NewGormLoggerWithConfig(config GormConfig) gormlogger.Interface
- func OperationFields(action, resource, resourceID string) []log.Field
- func ResultFields(result string, durationMS int64) []log.Field
- func StreamServerLoggingInterceptor() grpc.StreamServerInterceptor
- func StreamServerLoggingInterceptorWithConfig(config GRPCServerLoggerConfig) grpc.StreamServerInterceptor
- func UnaryServerLoggingInterceptor() grpc.UnaryServerInterceptor
- func UnaryServerLoggingInterceptorWithConfig(config GRPCServerLoggerConfig) grpc.UnaryServerInterceptor
- func UserFields(userID, accountID, tenantID string) []log.Field
- func WithLogger(ctx context.Context, logger *RequestLogger) context.Context
- type GRPCServerLoggerConfig
- type GormConfig
- type HTTPLoggerConfig
- type RedisHook
- type RedisHookConfig
- type RequestLogger
- func (l *RequestLogger) Debug(msg string, fields ...log.Field)
- func (l *RequestLogger) Debugw(msg string, keysAndValues ...interface{})
- func (l *RequestLogger) Error(msg string, fields ...log.Field)
- func (l *RequestLogger) Errorw(msg string, keysAndValues ...interface{})
- func (l *RequestLogger) Fields() []log.Field
- func (l *RequestLogger) Info(msg string, fields ...log.Field)
- func (l *RequestLogger) Infow(msg string, keysAndValues ...interface{})
- func (l *RequestLogger) Warn(msg string, fields ...log.Field)
- func (l *RequestLogger) Warnw(msg string, keysAndValues ...interface{})
- func (l *RequestLogger) WithField(key string, value interface{}) *RequestLogger
- func (l *RequestLogger) WithFields(fields ...log.Field) *RequestLogger
Constants ¶
const ( FieldTraceID = "trace_id" FieldSpanID = "span_id" FieldRequestID = "request_id" )
追踪相关字段
const ( FieldUserID = "user_id" FieldAccountID = "account_id" FieldTenantID = "tenant_id" FieldClientIP = "client_ip" FieldUserAgent = "user_agent" )
身份相关字段
const ( FieldAction = "action" FieldResource = "resource" FieldResourceID = "resource_id" FieldResult = "result" )
操作相关字段
const ( FieldDurationMS = "duration_ms" FieldLatency = "latency" )
性能相关字段
const ( FieldError = "error" FieldErrorCode = "error_code" FieldStackTrace = "stack_trace" )
错误相关字段
const ( FieldMethod = "method" FieldPath = "path" FieldQuery = "query" FieldStatusCode = "status_code" )
HTTP 相关字段
const ( FieldGRPCMethod = "grpc.method" FieldGRPCService = "grpc.service" FieldGRPCCode = "grpc.code" )
gRPC 相关字段
const ( ActionCreate = "create" ActionRead = "read" ActionUpdate = "update" ActionDelete = "delete" ActionList = "list" ActionLogin = "login" ActionLogout = "logout" ActionRegister = "register" ActionVerify = "verify" ActionRefresh = "refresh" ActionRevoke = "revoke" ActionBind = "bind" ActionUnbind = "unbind" )
const ( ResourceUser = "user" ResourceChild = "child" ResourceGuardianship = "guardianship" ResourceCredential = "credential" ResourceToken = "token" ResourceSession = "session" )
const ( ResultSuccess = "success" ResultFailed = "failed" ResultDenied = "denied" ResultTimeout = "timeout" )
const ( EventRequestStart = "request_start" EventRequestEnd = "request_end" EventOperation = "operation" EventAudit = "audit" EventSecurity = "security" EventPerformance = "performance" )
const ( GormSilent gormlogger.LogLevel = iota + 1 GormError GormWarn GormInfo )
GORM 日志级别
Variables ¶
This section is empty.
Functions ¶
func HTTPFields ¶
HTTPFields 生成 HTTP 相关字段
func HTTPLoggerWithConfig ¶
func HTTPLoggerWithConfig(config HTTPLoggerConfig) gin.HandlerFunc
HTTPLoggerWithConfig 返回带配置的 Gin HTTP 日志中间件
func NewGormLogger ¶
func NewGormLogger(level int) gormlogger.Interface
NewGormLogger 创建 GORM 日志适配器 将 GORM 的日志输出适配到 component-base 的类型化日志系统
func NewGormLoggerWithConfig ¶
func NewGormLoggerWithConfig(config GormConfig) gormlogger.Interface
NewGormLoggerWithConfig 使用指定配置创建 GORM 日志适配器
func OperationFields ¶
OperationFields 生成操作相关字段
func ResultFields ¶
ResultFields 生成操作结果字段
func StreamServerLoggingInterceptor ¶
func StreamServerLoggingInterceptor() grpc.StreamServerInterceptor
StreamServerLoggingInterceptor gRPC 流式服务端日志拦截器
func StreamServerLoggingInterceptorWithConfig ¶
func StreamServerLoggingInterceptorWithConfig(config GRPCServerLoggerConfig) grpc.StreamServerInterceptor
StreamServerLoggingInterceptorWithConfig 带配置的 gRPC 流式服务端日志拦截器
func UnaryServerLoggingInterceptor ¶
func UnaryServerLoggingInterceptor() grpc.UnaryServerInterceptor
UnaryServerLoggingInterceptor gRPC 一元服务端日志拦截器
func UnaryServerLoggingInterceptorWithConfig ¶
func UnaryServerLoggingInterceptorWithConfig(config GRPCServerLoggerConfig) grpc.UnaryServerInterceptor
UnaryServerLoggingInterceptorWithConfig 带配置的 gRPC 一元服务端日志拦截器
func UserFields ¶
UserFields 生成用户相关字段
func WithLogger ¶
func WithLogger(ctx context.Context, logger *RequestLogger) context.Context
WithLogger 将 RequestLogger 放入 context
Types ¶
type GRPCServerLoggerConfig ¶
type GRPCServerLoggerConfig struct {
// LogRequestPayload 是否记录请求载荷
LogRequestPayload bool
// LogResponsePayload 是否记录响应载荷
LogResponsePayload bool
// MaxPayloadSize 最大记录的载荷大小
MaxPayloadSize int
// SkipMethods 跳过日志记录的方法列表
SkipMethods []string
}
GRPCServerLoggerConfig gRPC 服务端日志配置
func DefaultGRPCServerLoggerConfig ¶
func DefaultGRPCServerLoggerConfig() GRPCServerLoggerConfig
DefaultGRPCServerLoggerConfig 默认 gRPC 服务端日志配置
type GormConfig ¶
type GormConfig struct {
// SlowThreshold 慢查询阈值,超过此时间会记录警告
SlowThreshold time.Duration
// Colorful 是否使用彩色输出(仅开发环境)
Colorful bool
// LogLevel 日志级别
LogLevel gormlogger.LogLevel
}
GormConfig 定义 GORM 日志配置
type HTTPLoggerConfig ¶
type HTTPLoggerConfig struct {
// Tag 日志标签
Tag string
// SkipPaths 跳过日志记录的路径
SkipPaths []string
// LogRequestHeaders 是否记录请求头
LogRequestHeaders bool
// LogRequestBody 是否记录请求体
LogRequestBody bool
// LogResponseHeaders 是否记录响应头
LogResponseHeaders bool
// LogResponseBody 是否记录响应体
LogResponseBody bool
// MaskSensitiveData 是否对敏感数据脱敏
MaskSensitiveData bool
// MaxBodyBytes 最大记录的 body 大小
MaxBodyBytes int64
// RequestIDKey context 中 Request ID 的 key
RequestIDKey string
}
HTTPLoggerConfig 定义 HTTP 日志中间件的可配置项
func DefaultHTTPLoggerConfig ¶
func DefaultHTTPLoggerConfig() HTTPLoggerConfig
DefaultHTTPLoggerConfig 返回默认配置
type RedisHook ¶
type RedisHook struct {
// contains filtered or unexported fields
}
RedisHook Redis 命令执行钩子 用于记录 Redis 命令执行情况,类似于 GORM logger
func NewRedisHook ¶
NewRedisHook 创建 Redis 钩子 enabled: 是否启用日志记录 slowThreshold: 慢命令阈值(超过此时间会记录警告)
func NewRedisHookWithConfig ¶
func NewRedisHookWithConfig(config RedisHookConfig) *RedisHook
NewRedisHookWithConfig 使用指定配置创建 Redis 钩子
func (*RedisHook) ProcessHook ¶
func (h *RedisHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook
ProcessHook 命令执行钩子
func (*RedisHook) ProcessPipelineHook ¶
func (h *RedisHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook
ProcessPipelineHook 管道命令钩子
type RedisHookConfig ¶
type RedisHookConfig struct {
// Enabled 是否启用日志记录
Enabled bool
// SlowThreshold 慢命令阈值(超过此时间会记录警告)
SlowThreshold time.Duration
}
RedisHookConfig Redis 钩子配置
func DefaultRedisHookConfig ¶
func DefaultRedisHookConfig() RedisHookConfig
DefaultRedisHookConfig 返回默认 Redis 钩子配置
type RequestLogger ¶
type RequestLogger struct {
// contains filtered or unexported fields
}
RequestLogger 请求范围的日志记录器 封装了 log.Logger,预设了追踪字段(trace_id, span_id, request_id 等)
func L ¶
func L(ctx context.Context) *RequestLogger
L 从 context 获取 RequestLogger 如果 context 中没有 Logger,返回一个带有追踪信息的默认 Logger
func NewRequestLogger ¶
func NewRequestLogger(ctx context.Context, fields ...log.Field) *RequestLogger
NewRequestLogger 创建请求范围的 Logger 自动从 context 中提取 trace_id, span_id, request_id 等追踪信息
func (*RequestLogger) Debug ¶
func (l *RequestLogger) Debug(msg string, fields ...log.Field)
Debug 记录 Debug 级别日志
func (*RequestLogger) Debugw ¶
func (l *RequestLogger) Debugw(msg string, keysAndValues ...interface{})
Debugw 记录 Debug 级别日志(key-value 格式)
func (*RequestLogger) Error ¶
func (l *RequestLogger) Error(msg string, fields ...log.Field)
Error 记录 Error 级别日志
func (*RequestLogger) Errorw ¶
func (l *RequestLogger) Errorw(msg string, keysAndValues ...interface{})
Errorw 记录 Error 级别日志(key-value 格式)
func (*RequestLogger) Fields ¶
func (l *RequestLogger) Fields() []log.Field
Fields 返回当前 Logger 的所有字段(只读)
func (*RequestLogger) Info ¶
func (l *RequestLogger) Info(msg string, fields ...log.Field)
Info 记录 Info 级别日志
func (*RequestLogger) Infow ¶
func (l *RequestLogger) Infow(msg string, keysAndValues ...interface{})
Infow 记录 Info 级别日志(key-value 格式)
func (*RequestLogger) Warn ¶
func (l *RequestLogger) Warn(msg string, fields ...log.Field)
Warn 记录 Warn 级别日志
func (*RequestLogger) Warnw ¶
func (l *RequestLogger) Warnw(msg string, keysAndValues ...interface{})
Warnw 记录 Warn 级别日志(key-value 格式)
func (*RequestLogger) WithField ¶
func (l *RequestLogger) WithField(key string, value interface{}) *RequestLogger
WithField 创建一个带有单个额外字段的新 Logger
func (*RequestLogger) WithFields ¶
func (l *RequestLogger) WithFields(fields ...log.Field) *RequestLogger
WithFields 创建一个带有额外字段的新 Logger(不可变设计)