Documentation
¶
Overview ¶
Package logger 是封装在 https://github.com/uber-go/zap 中的日志库
支持终端打印和日志保存 支持自动日志文件切割 支持 JSON 格式和控制台日志格式输出 支持 Debug, Info, Warn, Error, Panic, Fatal,也支持类似 fmt.Printf 的日志打印,Debugf, Infof, Warnf, Errorf, Panicf, Fatalf
Index ¶
- Constants
- func DebugWithCtx(ctx context.Context, msg string, fields ...Field)
- func ErrorWithCtx(ctx context.Context, msg string, fields ...Field)
- func ExecuteCustomHooksWithCtx(ctx context.Context, level zapcore.Level, msg string, fields ...Field) error
- func FatalWithCtx(ctx context.Context, msg string, fields ...Field)
- func Get() *zap.Logger
- func GetLogger(module string) *zap.Logger
- func GetLoggerByLevel(level string) *zap.Logger
- func GetWithSkip(skip int) *zap.Logger
- func InfoWithCtx(ctx context.Context, msg string, fields ...Field)
- func Init(opts ...Option) (*zap.Logger, error)
- func InitRouter(defaultLog *zap.Logger, routes []*RouteConfig, defaultConfig *RouteConfig) error
- func IsDebugEnabled() bool
- func IsInfoEnabled() bool
- func ModuleDebugWithCtx(ctx context.Context, module string, msg string, fields ...Field)
- func ModuleErrorWithCtx(ctx context.Context, module string, msg string, fields ...Field)
- func ModuleInfoWithCtx(ctx context.Context, module string, msg string, fields ...Field)
- func ModuleWarnWithCtx(ctx context.Context, module string, msg string, fields ...Field)
- func NewLoggerCollector() prometheus.Collector
- func PanicWithCtx(ctx context.Context, msg string, fields ...Field)
- func RecordDrop()
- func RegisterCloser(c Closer)
- func RegisterPrometheus()
- func ReplaceGRPCLoggerV2(l *zap.Logger)
- func RouterSync() error
- func Shutdown(_ context.Context) error
- func Sync() error
- func WarnWithCtx(ctx context.Context, msg string, fields ...Field)
- func WithCallerFunc(ctx context.Context, callerFunc string) context.Context
- type Closer
- type ContextKey
- type CustomHook
- type CustomHookWithCtx
- type Field
- func Any(key string, val interface{}) Field
- func Bool(key string, val bool) Field
- func Duration(key string, val time.Duration) Field
- func Err(err error) Field
- func Float64(key string, val float64) Field
- func Int(key string, val int) Field
- func Int32(key string, val int32) Field
- func Int64(key string, val int64) Field
- func Skip() Field
- func String(key string, val string) Field
- func Stringer(key string, val fmt.Stringer) Field
- func Time(key string, val time.Time) Field
- func Uint(key string, val uint) Field
- func Uint32(key string, val uint32) Field
- func Uint64(key string, val uint64) Field
- func Uintptr(key string, val uintptr) Field
- type FileOption
- func WithFileIsCompression(isCompression bool) FileOption
- func WithFileMaxAge(maxAge int) FileOption
- func WithFileMaxBackups(maxBackups int) FileOption
- func WithFileMaxSize(maxSize int) FileOption
- func WithFileName(filename string) FileOption
- func WithLocalTime(isLocalTime bool) FileOption
- func WithNoPrint(noPrint bool) FileOption
- func WithSaveDay(isSaveDay bool) FileOption
- type LogRouter
- type Metrics
- type Option
- func WithAsync(enabled bool) Option
- func WithAsyncBufferSize(size int) Option
- func WithAsyncFlushInterval(interval time.Duration) Option
- func WithCustomHooks(hooks ...CustomHook) Option
- func WithCustomHooksWithCtx(hooks ...CustomHookWithCtx) Option
- func WithFormat(format string) Option
- func WithHooks(hooks ...func(zapcore.Entry) error) Option
- func WithLevel(levelName string) Option
- func WithRoutes(routes []*RouteConfig) Option
- func WithSave(isSave bool, opts ...FileOption) Option
- type RouteConfig
- type SLSConfig
- type SLSHook
- func (h *SLSHook) Close() error
- func (h *SLSHook) GetMetrics() map[string]interface{}
- func (h *SLSHook) GetState() int32
- func (h *SLSHook) Hook(_ context.Context, entry zapcore.Entry, fields []Field) error
- func (h *SLSHook) IsHealthy() bool
- func (h *SLSHook) RecordFailure(err error)
- func (h *SLSHook) RecordSuccess()
Constants ¶
const ( StateCreated = 0 StateStarting = 1 StateRunning = 2 StateStopping = 3 StateStopped = 4 StateFailed = 5 )
ProducerState 生产者状态常量
Variables ¶
This section is empty.
Functions ¶
func DebugWithCtx ¶ added in v1.4.22
DebugWithCtx 调试级别日志(必须提供 context) 自动从 context 中提取 request_id、trace_id 等链路追踪信息
func ErrorWithCtx ¶ added in v1.4.22
ErrorWithCtx 错误级别日志(必须提供 context)
func ExecuteCustomHooksWithCtx ¶ added in v1.4.22
func ExecuteCustomHooksWithCtx(ctx context.Context, level zapcore.Level, msg string, fields ...Field) error
ExecuteCustomHooksWithCtx 手动执行带 Context 的自定义钩子 用法: 在业务代码中调用此函数来执行需要访问 context 的钩子 示例:
ctx := context.WithValue(context.Background(), logger.ContextKeyForRequestID(), "12345")
logger.ExecuteCustomHooksWithCtx(ctx, zapcore.InfoLevel, "user login", logger.String("user_id", "123"))
func FatalWithCtx ¶ added in v1.4.22
FatalWithCtx fatal 级别日志(必须提供 context)
func GetLoggerByLevel ¶ added in v1.4.22
GetLoggerByLevel 根据日志级别获取对应的 logger
func GetWithSkip ¶
GetWithSkip 获取 defaultLogger,设置跳过的调用者值,自定义显示的代码行数
func InfoWithCtx ¶ added in v1.4.22
InfoWithCtx 信息级别日志(必须提供 context)
func Init ¶
Init 初始化日志设置
默认行为:保存到文件 logs/app.log,JSON 格式,info 级别,异步写入。 因此 Init() 会静默创建日志目录并写文件,而不是输出到终端。
终端输出(开发环境常用),示例: Init(WithSave(false), WithFormat("console")) 调整日志级别(仍默认写文件,如需终端输出请配合 WithSave(false)),示例: Init(WithLevel("debug")) 带钩子的日志,示例: Init(WithHooks(func(zapcore.Entry) error{return nil})) 输出日志到指定文件,自定义设置日志文件切割参数,json 格式,示例: Init(
WithFormat("json"),
WithSave(true,
WithFileName("my.log"),
WithFileMaxSize(5),
WithFileMaxBackups(5),
WithFileMaxAge(10),
WithFileIsCompression(true),
))
func InitRouter ¶ added in v1.4.22
func InitRouter(defaultLog *zap.Logger, routes []*RouteConfig, defaultConfig *RouteConfig) error
InitRouter 初始化全局日志路由器 defaultConfig: 默认配置,路由配置中未指定的字段将继承此配置 注意: 受 routerOnce 保护,仅首次调用生效;初始化后再次携带 routes 调用不会重配路由, 会返回明确错误(而非静默 no-op),增量注册请使用 LogRouter.RegisterRoute
func IsDebugEnabled ¶ added in v1.4.22
func IsDebugEnabled() bool
IsDebugEnabled 检查是否启用了 DEBUG 级别日志 用于性能敏感场景,避免不必要的字符串拼接或对象创建
func ModuleDebugWithCtx ¶ added in v1.4.22
ModuleDebugWithCtx 按模块记录调试日志(带Context)
func ModuleErrorWithCtx ¶ added in v1.4.22
ModuleErrorWithCtx 按模块记录错误日志(带Context)
func ModuleInfoWithCtx ¶ added in v1.4.22
ModuleInfoWithCtx 按模块记录信息日志(带Context)
func ModuleWarnWithCtx ¶ added in v1.4.22
ModuleWarnWithCtx 按模块记录警告日志(带Context)
func NewLoggerCollector ¶ added in v1.4.52
func NewLoggerCollector() prometheus.Collector
NewLoggerCollector 创建 logger Prometheus Collector 用法:
prometheus.MustRegister(logger.NewLoggerCollector())
func PanicWithCtx ¶ added in v1.4.22
PanicWithCtx panic 级别日志(必须提供 context)
func RecordDrop ¶ added in v1.4.52
func RecordDrop()
RecordDrop 记录一次日志丢弃(由自定义 WriteSyncer wrapper 调用) 用法: 实现自定义 zapcore.WriteSyncer,在 Write 返回 error 时调用 logger.RecordDrop()
func RegisterCloser ¶ added in v1.4.52
func RegisterCloser(c Closer)
RegisterCloser 注册一个需要在 Shutdown 时关闭的资源 典型用法: logger.RegisterCloser(slsHook)
func RegisterPrometheus ¶ added in v1.4.52
func RegisterPrometheus()
RegisterPrometheus 注册 logger 指标到 Prometheus 在 initApp.go 中调用一次即可,之后 /metrics 端点自动包含 logger 指标
logger.RegisterPrometheus()
func ReplaceGRPCLoggerV2 ¶
ReplaceGRPCLoggerV2 替换 gRPC 默认日志记录器为 zap 实现
func Shutdown ¶ added in v1.4.52
Shutdown 优雅关闭日志系统,确保所有缓冲数据写入完成 关闭顺序: 已注册的 Closer → 路由器 → 默认 logger 推荐在应用 main 函数的 defer 中调用:
defer logger.Shutdown(context.Background())
func WarnWithCtx ¶ added in v1.4.22
WarnWithCtx 警告级别日志(必须提供 context)
Types ¶
type Closer ¶ added in v1.4.52
type Closer interface {
Close() error
}
Closer 可关闭资源的接口,用于 Shutdown 时统一清理
type ContextKey ¶ added in v1.4.22
type ContextKey string
ContextKey context key 类型 (供外部包使用)
const ContextKeyCallerFunc ContextKey = "caller_func"
ContextKeyCallerFunc caller_func 的 context key 常量
const ContextKeyRequestID ContextKey = "request_id"
ContextKeyRequestID request_id 的 context key 常量
func ContextKeyForCallerFunc ¶ added in v1.4.23
func ContextKeyForCallerFunc() ContextKey
ContextKeyForCallerFunc 返回用于存储 caller_func 的 context key 供各组件(GORM、Redis 等)在日志中使用,确保统一
func ContextKeyForRequestID ¶ added in v1.4.22
func ContextKeyForRequestID() ContextKey
ContextKeyForRequestID 返回用于存储 request_id 的 context key 供 middleware 包在注入 request_id 时使用,确保与 logger 包一致
type CustomHook ¶ added in v1.3.12
CustomHook 自定义钩子函数,可访问日志级别、消息和字段
type CustomHookWithCtx ¶ added in v1.4.22
CustomHookWithCtx 带 Context 的自定义钩子函数,可访问上下文、日志级别、消息和字段 钩子可从 context 中提取 request_id、trace_id 等链路追踪信息
type FileOption ¶
type FileOption func(*fileOptions)
FileOption 文件配置选项函数类型
func WithFileIsCompression ¶
func WithFileIsCompression(isCompression bool) FileOption
WithFileIsCompression 设置是否压缩日志文件
func WithFileMaxBackups ¶
func WithFileMaxBackups(maxBackups int) FileOption
WithFileMaxBackups 设置旧文件最大保留数量
func WithLocalTime ¶ added in v1.1.18
func WithLocalTime(isLocalTime bool) FileOption
WithLocalTime 设置是否使用本地时间
func WithNoPrint ¶ added in v1.3.2
func WithNoPrint(noPrint bool) FileOption
WithNoPrint 设置是否禁用控制台输出
func WithSaveDay ¶ added in v1.1.50
func WithSaveDay(isSaveDay bool) FileOption
WithSaveDay 设置是否按天保存日志文件
type LogRouter ¶ added in v1.4.22
type LogRouter struct {
// contains filtered or unexported fields
}
LogRouter 日志路由器 - 支持按模块/级别动态路由到不同文件
func (*LogRouter) RegisterRoute ¶ added in v1.4.22
func (r *LogRouter) RegisterRoute(config *RouteConfig) error
RegisterRoute 注册一个日志路由
type Metrics ¶ added in v1.4.52
type Metrics struct {
// DroppedEntries 异步缓冲区满时丢弃的日志条数
DroppedEntries int64
// RouterLoggerCount 路由器中活跃的 logger 数量
RouterLoggerCount int
}
Metrics 日志系统运行时指标快照 可对接 Prometheus / 自定义监控采集
func GetMetrics ¶ added in v1.4.52
func GetMetrics() Metrics
GetMetrics 获取日志系统运行时指标快照 用于 Prometheus exporter 或 /metrics 端点暴露
type Option ¶
type Option func(*options)
Option 日志配置选项函数类型
func WithAsyncBufferSize ¶ added in v1.4.3
WithAsyncBufferSize 设置异步日志缓冲区大小(字节)
func WithAsyncFlushInterval ¶ added in v1.4.3
WithAsyncFlushInterval 设置异步日志刷新间隔
func WithCustomHooks ¶ added in v1.3.12
func WithCustomHooks(hooks ...CustomHook) Option
WithCustomHooks 设置可访问字段数据的自定义钩子
func WithCustomHooksWithCtx ¶ added in v1.4.22
func WithCustomHooksWithCtx(hooks ...CustomHookWithCtx) Option
WithCustomHooksWithCtx 设置可访问 Context 和字段数据的自定义钩子 钩子可从 context 中提取 request_id、trace_id 等链路追踪信息
func WithRoutes ¶ added in v1.4.22
func WithRoutes(routes []*RouteConfig) Option
WithRoutes 设置日志路由配置
type RouteConfig ¶ added in v1.4.22
type RouteConfig struct {
Module string
Filename string // 支持完整路径或相对路径 (如: "/var/log/order.log" 或 "order.log")
Level string
MaxSize int
MaxBackups int
MaxAge int
IsCompression bool
IsSaveDay bool
Format string
IsAsync bool
}
RouteConfig 路由配置
type SLSConfig ¶ added in v1.4.22
type SLSConfig struct {
// 必选参数
Endpoint string // SLS Endpoint,如: cn-hangzhou.log.aliyuncs.com
AccessKeyID string // AccessKey ID
AccessKeySecret string // AccessKey Secret
ProjectName string // SLS Project 名称
LogStoreName string // LogStore 名称
// 可选参数
Topic string // 日志主题,默认为空
Source string // 日志来源,默认为服务名称
MaxRetries int // 最大重试次数,默认 10(已接线到 producerConfig.Retries)
Timeout int // 预留字段:aliyun-log-go-sdk 的 ProducerConfig 未暴露对应超时项,当前仅做取值范围校验、不影响发送
// Producer 性能配置
TotalSizeLnBytes int64 // 缓存总大小(字节),默认 512MB (512 * 1024 * 1024)
MaxBatchCount int // 单个 Batch 最大日志条数,默认 4096
MaxBatchSize int // 单个 Batch 最大大小(字节),默认 3MB (3 * 1024 * 1024)
LingerMs int // Batch 刷新间隔(毫秒),默认 2000ms
DisableRuntimeMetrics bool // 禁用运行时指标日志,默认 true
// 高级配置(大厂最佳实践)
EnableHealthCheck bool // 是否启用健康检查,默认 false(关闭),true 表示开启
HealthCheckInterval int // 健康检查间隔(秒),默认 30 秒
SendTimeout int // 预留字段:发送超时(秒);SDK ProducerConfig 未暴露对应项,当前仅做取值校验、不影响发送
SkipVerify bool // 是否跳过启动时的 Producer 就绪校验,默认 false;校验已不再向 LogStore 写入测试日志,故无需为“避免污染”而显式置 true
}
SLSConfig 阿里云 SLS 配置
type SLSHook ¶ added in v1.4.22
type SLSHook struct {
// contains filtered or unexported fields
}
SLSHook 阿里云 SLS 日志钩子
func NewSLSHook ¶ added in v1.4.22
NewSLSHook 创建阿里云 SLS 日志钩子 用法:
config := &SLSConfig{
Endpoint: "cn-hangzhou.log.aliyuncs.com",
AccessKeyID: "your-access-key-id",
AccessKeySecret: "your-access-key-secret",
ProjectName: "your-project",
LogStoreName: "your-logstore",
Source: "user-service",
}
hook, err := NewSLSHook(config)
if err != nil {
panic(err)
}
logger.Init(logger.WithCustomHooksWithCtx(hook.Hook))
func (*SLSHook) GetMetrics ¶ added in v1.4.22
GetMetrics 获取监控指标(用于 Prometheus 等监控系统)
func (*SLSHook) RecordFailure ¶ added in v1.4.22
RecordFailure 记录一次发送失败并保存错误信息
func (*SLSHook) RecordSuccess ¶ added in v1.4.22
func (h *SLSHook) RecordSuccess()
RecordSuccess 记录一次发送成功