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 MongoHook
- type MongoHookConfig
- 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 MongoHook ¶ added in v0.4.0
type MongoHook struct {
// contains filtered or unexported fields
}
MongoHook MongoDB 命令执行钩子 用于记录 MongoDB 命令执行情况,类似于 GORM logger 和 Redis Hook
func NewMongoHook ¶ added in v0.4.0
NewMongoHook 创建 MongoDB 钩子 enabled: 是否启用日志记录 slowThreshold: 慢命令阈值(超过此时间会记录警告)
func NewMongoHookWithConfig ¶ added in v0.4.0
func NewMongoHookWithConfig(config MongoHookConfig) *MongoHook
NewMongoHookWithConfig 使用指定配置创建 MongoDB 钩子
func (*MongoHook) CommandMonitor ¶ added in v0.4.0
func (h *MongoHook) CommandMonitor() *event.CommandMonitor
CommandMonitor 返回 MongoDB 命令监控器 用于监控所有 MongoDB 命令的执行
func (*MongoHook) PoolMonitor ¶ added in v0.4.0
func (h *MongoHook) PoolMonitor() *event.PoolMonitor
PoolMonitor 返回 MongoDB 连接池监控器 用于监控连接池的创建、关闭等事件
func (*MongoHook) ServerMonitor ¶ added in v0.4.0
func (h *MongoHook) ServerMonitor() *event.ServerMonitor
ServerMonitor 返回 MongoDB 服务器监控器 用于监控服务器心跳、状态变更等事件
type MongoHookConfig ¶ added in v0.4.0
type MongoHookConfig struct {
// Enabled 是否启用日志记录
Enabled bool
// SlowThreshold 慢命令阈值(超过此时间会记录警告)
SlowThreshold time.Duration
// LogCommandDetail 是否记录命令详情(建议仅在调试时开启)
LogCommandDetail bool
// LogReplyDetail 是否记录响应详情(建议仅在调试时开启)
LogReplyDetail bool
// LogHeartbeat 是否记录心跳日志(默认 false)
LogHeartbeat bool
// LogStarted 是否记录命令开始日志(默认 false,只记录完成)
LogStarted bool
// IgnoredCommands 忽略的命令列表(降噪)
IgnoredCommands []string
// SlowReadThreshold 慢读命令阈值(0 表示使用 SlowThreshold)
SlowReadThreshold time.Duration
// SlowWriteThreshold 慢写命令阈值(0 表示使用 SlowThreshold)
SlowWriteThreshold time.Duration
}
MongoHookConfig MongoDB 钩子配置
func DefaultMongoHookConfig ¶ added in v0.4.0
func DefaultMongoHookConfig() MongoHookConfig
DefaultMongoHookConfig 返回默认 MongoDB 钩子配置
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 Default ¶ added in v0.4.0
func Default() *RequestLogger
Default 返回默认的 RequestLogger(无上下文场景使用) 适用场景: - 程序启动初始化 - 后台任务/定时任务 - 独立的 goroutine - 不在请求链路中的日志记录
示例:
logger.Default().Info("Application started")
logger.Default().WithField("version", "1.0.0").Info("Service initialized")
func L ¶
func L(ctx context.Context) *RequestLogger
L 从 context 获取 RequestLogger 如果 context 中没有 Logger,返回一个带有追踪信息的默认 Logger
func New ¶ added in v0.4.0
func New(fields ...log.Field) *RequestLogger
New 创建一个带有自定义字段的 RequestLogger(无上下文场景使用) 适用于需要预设一些固定字段的场景,如: - 后台任务标识 - 模块名称 - 服务名称
示例:
taskLogger := logger.New(log.String("task", "data_sync"), log.String("module", "background"))
taskLogger.Info("Task started")
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(不可变设计)