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 ModuleLogWithCtx(ctx context.Context, module string, levelFunc func(string, ...Field), ...)
- func ModuleWarnWithCtx(ctx context.Context, module string, msg string, fields ...Field)
- func PanicWithCtx(ctx context.Context, msg string, fields ...Field)
- func ReplaceGRPCLoggerV2(l *zap.Logger)
- func RouterSync() error
- func Sync() error
- func WarnWithCtx(ctx context.Context, msg string, fields ...Field)
- func WithCallerFunc(ctx context.Context, callerFunc string) context.Context
- 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 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(ctx 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 等链路追踪信息 自动执行 customHooksWithCtx(如 SLS 日志上报)
func ErrorWithCtx ¶ added in v1.4.22
ErrorWithCtx 错误级别日志(必须提供 context) 自动从 context 中提取 request_id、trace_id 等链路追踪信息 自动执行 customHooksWithCtx(如 SLS 日志上报)
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) 自动从 context 中提取 request_id、trace_id 等链路追踪信息 自动执行 customHooksWithCtx(如 SLS 日志上报)
func GetLoggerByLevel ¶ added in v1.4.22
GetLoggerByLevel 根据日志级别获取对应的 logger
func GetWithSkip ¶
GetWithSkip 获取 defaultLogger,设置跳过的调用者值,自定义显示的代码行数
func InfoWithCtx ¶ added in v1.4.22
InfoWithCtx 信息级别日志(必须提供 context) 自动从 context 中提取 request_id、trace_id 等链路追踪信息 自动执行 customHooksWithCtx(如 SLS 日志上报)
func Init ¶
Init 初始化日志设置 在终端打印 debug 级别日志,示例: Init() 在终端打印 info 级别日志,示例: Init(WithLevel("info")) 在终端打印 json 格式,debug 级别日志,示例: Init(WithFormat("json")) 带钩子的日志,示例: Init(WithHooks(func(zapcore.Entry) error{return nil})) 输出日志到文件 out.log,使用默认切割日志相关参数,debug 级别日志,示例: Init(WithSave()) 输出日志到指定文件,自定义设置日志文件切割参数,json 格式,debug 级别日志,示例: 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: 默认配置,路由配置中未指定的字段将继承此配置
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 ModuleLogWithCtx ¶ added in v1.4.22
func ModuleLogWithCtx(ctx context.Context, module string, levelFunc func(string, ...Field), msg string, fields ...Field)
ModuleLogWithCtx 按模块记录日志(带Context) - 自动提取 request_id/trace_id 用法: logger.ModuleErrorWithCtx(ctx, "order", "订单创建失败", logger.Err(err))
func ModuleWarnWithCtx ¶ added in v1.4.22
ModuleWarnWithCtx 按模块记录警告日志(带Context)
func PanicWithCtx ¶ added in v1.4.22
PanicWithCtx panic 级别日志(必须提供 context) 自动从 context 中提取 request_id、trace_id 等链路追踪信息 自动执行 customHooksWithCtx(如 SLS 日志上报)
func ReplaceGRPCLoggerV2 ¶
ReplaceGRPCLoggerV2 replace grpc logger v2
func Sync ¶
func Sync() error
Sync flushing any buffered log entries, applications should take care to call Sync before exiting.
func WarnWithCtx ¶ added in v1.4.22
WarnWithCtx 警告级别日志(必须提供 context) 自动从 context 中提取 request_id、trace_id 等链路追踪信息 自动执行 customHooksWithCtx(如 SLS 日志上报)
Types ¶
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 defines a custom hook function that can access log level, message and fields
type CustomHookWithCtx ¶ added in v1.4.22
CustomHookWithCtx defines a custom hook function that can access context, log level, message and fields This allows hooks to extract request_id, trace_id and other context values
type Field ¶
Field type
type FileOption ¶
type FileOption func(*fileOptions)
FileOption set the file options.
func WithFileIsCompression ¶
func WithFileIsCompression(isCompression bool) FileOption
WithFileIsCompression set whether to compress log files
func WithFileMaxAge ¶
func WithFileMaxAge(maxAge int) FileOption
WithFileMaxAge set maximum number of days for old documents
func WithFileMaxBackups ¶
func WithFileMaxBackups(maxBackups int) FileOption
WithFileMaxBackups set maximum number of old files
func WithFileMaxSize ¶
func WithFileMaxSize(maxSize int) FileOption
WithFileMaxSize set maximum file size (MB)
func WithLocalTime ¶ added in v1.1.18
func WithLocalTime(isLocalTime bool) FileOption
WithLocalTime set whether to use local time
func WithNoPrint ¶ added in v1.3.2
func WithNoPrint(noPrint bool) FileOption
func WithSaveDay ¶ added in v1.1.50
func WithSaveDay(isSaveDay bool) FileOption
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 Option ¶
type Option func(*options)
Option set the logger options.
func WithAsyncBufferSize ¶ added in v1.4.3
WithAsyncBufferSize sets the buffer size for asynchronous logging (in bytes)
func WithAsyncFlushInterval ¶ added in v1.4.3
WithAsyncFlushInterval sets the flush interval for asynchronous logging
func WithCustomHooks ¶ added in v1.3.12
func WithCustomHooks(hooks ...CustomHook) Option
WithCustomHooks sets custom hooks that can access fields data
func WithCustomHooksWithCtx ¶ added in v1.4.22
func WithCustomHooksWithCtx(hooks ...CustomHookWithCtx) Option
WithCustomHooksWithCtx sets custom hooks that can access context and fields data This allows hooks to extract request_id, trace_id from context
func WithFormat ¶
WithFormat set the output log format, console or json
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
Timeout int // 超时时间(秒),默认 60
// 高级配置(大厂最佳实践)
EnableHealthCheck bool // 是否启用健康检查,默认 false(关闭),true 表示开启
HealthCheckInterval time.Duration // 健康检查间隔,默认 30 秒
SendTimeout time.Duration // 发送超时时间,默认 5 秒
}
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 记录发送成功(供内部使用)