logger

package
v1.4.24 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 21, 2026 License: MIT Imports: 19 Imported by: 0

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

View Source
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

func DebugWithCtx(ctx context.Context, msg string, fields ...Field)

DebugWithCtx 调试级别日志(必须提供 context) 自动从 context 中提取 request_id、trace_id 等链路追踪信息 自动执行 customHooksWithCtx(如 SLS 日志上报)

func ErrorWithCtx added in v1.4.22

func ErrorWithCtx(ctx context.Context, msg string, fields ...Field)

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

func FatalWithCtx(ctx context.Context, msg string, fields ...Field)

FatalWithCtx fatal 级别日志(必须提供 context) 自动从 context 中提取 request_id、trace_id 等链路追踪信息 自动执行 customHooksWithCtx(如 SLS 日志上报)

func Get

func Get() *zap.Logger

Get 获取日志记录器

func GetLogger added in v1.4.22

func GetLogger(module string) *zap.Logger

GetLogger 根据模块名获取对应的 logger

func GetLoggerByLevel added in v1.4.22

func GetLoggerByLevel(level string) *zap.Logger

GetLoggerByLevel 根据日志级别获取对应的 logger

func GetWithSkip

func GetWithSkip(skip int) *zap.Logger

GetWithSkip 获取 defaultLogger,设置跳过的调用者值,自定义显示的代码行数

func InfoWithCtx added in v1.4.22

func InfoWithCtx(ctx context.Context, msg string, fields ...Field)

InfoWithCtx 信息级别日志(必须提供 context) 自动从 context 中提取 request_id、trace_id 等链路追踪信息 自动执行 customHooksWithCtx(如 SLS 日志上报)

func Init

func Init(opts ...Option) (*zap.Logger, error)

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 IsInfoEnabled added in v1.4.22

func IsInfoEnabled() bool

IsInfoEnabled 检查是否启用了 INFO 级别日志

func ModuleDebugWithCtx added in v1.4.22

func ModuleDebugWithCtx(ctx context.Context, module string, msg string, fields ...Field)

ModuleDebugWithCtx 按模块记录调试日志(带Context)

func ModuleErrorWithCtx added in v1.4.22

func ModuleErrorWithCtx(ctx context.Context, module string, msg string, fields ...Field)

ModuleErrorWithCtx 按模块记录错误日志(带Context)

func ModuleInfoWithCtx added in v1.4.22

func ModuleInfoWithCtx(ctx context.Context, module string, msg string, fields ...Field)

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

func ModuleWarnWithCtx(ctx context.Context, module string, msg string, fields ...Field)

ModuleWarnWithCtx 按模块记录警告日志(带Context)

func PanicWithCtx added in v1.4.22

func PanicWithCtx(ctx context.Context, msg string, fields ...Field)

PanicWithCtx panic 级别日志(必须提供 context) 自动从 context 中提取 request_id、trace_id 等链路追踪信息 自动执行 customHooksWithCtx(如 SLS 日志上报)

func ReplaceGRPCLoggerV2

func ReplaceGRPCLoggerV2(l *zap.Logger)

ReplaceGRPCLoggerV2 replace grpc logger v2

func RouterSync added in v1.4.22

func RouterSync() error

RouterSync 同步全局路由器的所有 logger + 默认 logger

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

func WarnWithCtx(ctx context.Context, msg string, fields ...Field)

WarnWithCtx 警告级别日志(必须提供 context) 自动从 context 中提取 request_id、trace_id 等链路追踪信息 自动执行 customHooksWithCtx(如 SLS 日志上报)

func WithCallerFunc added in v1.4.23

func WithCallerFunc(ctx context.Context, callerFunc string) context.Context

WithCallerFunc 将调用者方法名注入到 context 中 使用示例:

ctx = logger.WithCallerFunc(ctx, "UserService.GetUser")
db.WithContext(ctx).First(&user, id)

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

type CustomHook func(entry zapcore.Entry, fields []Field) error

CustomHook defines a custom hook function that can access log level, message and fields

type CustomHookWithCtx added in v1.4.22

type CustomHookWithCtx func(ctx context.Context, entry zapcore.Entry, fields []Field) error

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

type Field = zapcore.Field

Field type

func Any

func Any(key string, val interface{}) Field

Any type, if it is a composite type such as object, slice, map, etc., use Any For better performance and readability, prefer using specific type functions when possible

func Bool

func Bool(key string, val bool) Field

Bool type

func Duration

func Duration(key string, val time.Duration) Field

Duration type

func Err

func Err(err error) Field

Err type

func Float64

func Float64(key string, val float64) Field

Float64 type

func Int

func Int(key string, val int) Field

Int type

func Int32 added in v1.0.5

func Int32(key string, val int32) Field

Int32 type

func Int64

func Int64(key string, val int64) Field

Int64 type

func Skip added in v1.4.22

func Skip() Field

Skip skips the field

func String

func String(key string, val string) Field

String type

func Stringer

func Stringer(key string, val fmt.Stringer) Field

Stringer type

func Time

func Time(key string, val time.Time) Field

Time type

func Uint

func Uint(key string, val uint) Field

Uint type

func Uint32 added in v1.0.5

func Uint32(key string, val uint32) Field

Uint32 type

func Uint64

func Uint64(key string, val uint64) Field

Uint64 type

func Uintptr

func Uintptr(key string, val uintptr) Field

Uintptr 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 WithFileName

func WithFileName(filename string) FileOption

WithFileName set log filename

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) Close added in v1.4.22

func (r *LogRouter) Close() error

Close 关闭所有 logger

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 WithAsync added in v1.4.3

func WithAsync(enabled bool) Option

WithAsync enables asynchronous logging

func WithAsyncBufferSize added in v1.4.3

func WithAsyncBufferSize(size int) Option

WithAsyncBufferSize sets the buffer size for asynchronous logging (in bytes)

func WithAsyncFlushInterval added in v1.4.3

func WithAsyncFlushInterval(interval time.Duration) Option

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

func WithFormat(format string) Option

WithFormat set the output log format, console or json

func WithHooks

func WithHooks(hooks ...func(zapcore.Entry) error) Option

WithHooks set the log hooks

func WithLevel

func WithLevel(levelName string) Option

WithLevel setting the log level

func WithRoutes added in v1.4.22

func WithRoutes(routes []*RouteConfig) Option

WithRoutes 设置日志路由配置

func WithSave

func WithSave(isSave bool, opts ...FileOption) Option

WithSave save log to file

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

func NewSLSHook(config *SLSConfig) (*SLSHook, error)

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) Close added in v1.4.22

func (h *SLSHook) Close() error

Close 关闭 SLS Producer,确保所有日志都被发送

func (*SLSHook) GetMetrics added in v1.4.22

func (h *SLSHook) GetMetrics() map[string]interface{}

GetMetrics 获取监控指标(用于 Prometheus 等监控系统)

func (*SLSHook) GetState added in v1.4.22

func (h *SLSHook) GetState() int32

GetState 获取当前状态(用于监控)

func (*SLSHook) Hook added in v1.4.22

func (h *SLSHook) Hook(ctx context.Context, entry zapcore.Entry, fields []Field) error

Hook 实现 CustomHookWithCtx 接口

func (*SLSHook) IsHealthy added in v1.4.22

func (h *SLSHook) IsHealthy() bool

IsHealthy 检查 SLS Hook 是否健康

func (*SLSHook) RecordFailure added in v1.4.22

func (h *SLSHook) RecordFailure(err error)

RecordFailure 记录发送失败(供内部使用)

func (*SLSHook) RecordSuccess added in v1.4.22

func (h *SLSHook) RecordSuccess()

RecordSuccess 记录发送成功(供内部使用)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL