logger

package
v1.4.52 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 21 Imported by: 0

README

Logger 日志包

基于 uber-go/zap 封装的高性能结构化日志库,支持异步写入、文件切割、日志路由、SLS 上报、链路追踪集成。

功能特性

特性 说明
结构化日志 JSON / Console 两种格式,字段类型安全
Context 传递 自动提取 request_id、trace_id、span_id、caller_func
异步写入 BufferedWriteSyncer,默认 8MB 缓冲区,性能提升 155%
文件切割 lumberjack / rotatelogs,支持按大小或按天切割
日志路由 按模块/级别路由到不同文件(如 order.log、payment.log)
SLS 上报 阿里云 SLS 异步上报,支持 Warn 级别过滤
优雅关闭 Closer 接口 + Shutdown 统一清理
运行时指标 Prometheus Collector,暴露丢弃数/活跃 logger 数
并发安全 sync.Once + atomic + RWMutex,全局单例

快速开始

基础用法
import "github.com/18721889353/sunshine/pkg/logger"

// 初始化(默认行为:保存日志到 logs/app.log,JSON 格式,info 级别,异步写入)
logger.Init()

// 终端输出(开发环境常用):显式关闭文件保存
logger.Init(logger.WithSave(false), logger.WithFormat("console"))

// 带 context 的日志(request_id 自动注入;trace_id/span_id 需 ctx 携带真实 OTel SpanContext)
ctx = context.WithValue(ctx, logger.ContextKeyForRequestID(), "req-001")
logger.InfoWithCtx(ctx, "用户登录", logger.String("user_id", "123"))
生产配置
logger.Init(
    logger.WithLevel("info"),
    logger.WithFormat("json"),
    logger.WithAsync(true),
    logger.WithSave(true,
        logger.WithFileName("logs/app.log"),
        logger.WithFileMaxSize(100),
        logger.WithFileMaxBackups(30),
        logger.WithFileMaxAge(7),
        logger.WithFileIsCompression(true),
        logger.WithSaveDay(true),
    ),
)
日志路由(按模块分文件)
logger.Init(
    logger.WithSave(true, ...),
    logger.WithRoutes([]*logger.RouteConfig{
        {
            Module:   "order",
            Filename: "logs/order/order.log",
            MaxSize:  200,
            IsAsync:  true,
        },
        {
            Module:   "payment",
            Filename: "logs/payment/payment.log",
            MaxSize:  50,
            IsAsync:  true,
        },
    }),
)

// 使用:自动路由到 order.log
logger.ModuleInfoWithCtx(ctx, "order", "订单创建", logger.String("id", "001"))
SLS 上报
hook, err := logger.NewSLSHook(&logger.SLSConfig{
    Endpoint:        "cn-shanghai.log.aliyuncs.com",
    AccessKeyID:     "your-key",
    AccessKeySecret: "your-secret",
    ProjectName:     "your-project",
    LogStoreName:    "your-logstore",
})
if err != nil {
    panic(err)
}
defer hook.Close()

// 注册 Hook(只上报 Warn 及以上)
logger.Init(
    logger.WithCustomHooksWithCtx(func(ctx context.Context, entry zapcore.Entry, fields []logger.Field) error {
        if entry.Level < zapcore.WarnLevel {
            return nil // Info/Debug 不上报 SLS
        }
        return hook.Hook(ctx, entry, fields)
    }),
)

就绪校验不写测试日志:NewSLSHook 启动时的 verifyProducerState 只校验 producer 句柄/状态, 不会向 LogStore 写入 health-check 测试日志(历史上会污染生产数据,且因 SendLog 异步属假验证,已移除)。

级别门控说明:带 ctx 的钩子(customHooksWithCtx)现与 zap core 上的 customHooks 行为一致, 仅当该日志级别被 Core().Enabled(level) 启用时才会执行——即 WithLevel("info") 下 DebugWithCtx 不会触发 SLS 上报, 也不会产生字段提取分配。上述 entry.Level < zapcore.WarnLevel 的包裹仍是「只上报 Warn 及以上」所需的最小过滤。

优雅关闭
// 注册 SLS Hook 到 logger(Shutdown 时自动关闭)
logger.RegisterCloser(hook)

// 应用退出时
defer logger.Shutdown(context.Background())
Prometheus 指标
// 注册后 /metrics 端点自动包含 logger 指标
logger.RegisterPrometheus()

暴露的指标:

指标名 类型 说明
logger_dropped_entries_total Counter 异步缓冲区满时丢弃的日志条数
logger_router_active_loggers Gauge 路由器中活跃的 logger 数量

API 一览

日志方法
方法 说明
DebugWithCtx(ctx, msg, fields...) 调试级别
InfoWithCtx(ctx, msg, fields...) 信息级别
WarnWithCtx(ctx, msg, fields...) 警告级别
ErrorWithCtx(ctx, msg, fields...) 错误级别
PanicWithCtx(ctx, msg, fields...) Panic 级别
FatalWithCtx(ctx, msg, fields...) Fatal 级别
ModuleInfoWithCtx(ctx, module, msg, fields...) 按模块记录
ModuleErrorWithCtx(ctx, module, msg, fields...) 按模块记录
字段函数
函数 说明
String(key, val) 字符串
Int(key, val) 整数
Int64(key, val) 64 位整数
Float64(key, val) 浮点数
Bool(key, val) 布尔
Err(err) 错误(nil 时自动跳过)
Duration(key, val) 时间间隔
Any(key, val) 任意类型
配置函数
函数 说明
WithLevel(level) 日志级别:debug/info/warn/error
WithFormat(format) 输出格式:json/console
WithSave(isSave, opts...) 是否保存到文件
WithAsync(enabled) 是否异步写入
WithAsyncBufferSize(size) 异步缓冲区大小(字节)
WithAsyncFlushInterval(d) 异步刷新间隔
WithRoutes(routes) 日志路由配置
WithCustomHooksWithCtx(hooks...) 带 Context 的自定义钩子
文件配置
函数 说明
WithFileName(name) 文件名
WithFileMaxSize(mb) 最大文件大小(MB)
WithFileMaxBackups(n) 最大备份数
WithFileMaxAge(days) 最大保留天数
WithFileIsCompression(on) 是否压缩
WithSaveDay(on) 是否按天保存
WithNoPrint(on) 禁止终端输出
工具函数
函数 说明
IsDebugEnabled() 检查 DEBUG 是否开启
IsInfoEnabled() 检查 INFO 是否开启
GetMetrics() 获取运行时指标快照
RecordDrop() 记录一次日志丢弃
RegisterPrometheus() 注册 Prometheus 指标
RegisterCloser(c) 注册 Shutdown 时关闭的资源
Shutdown(ctx) 优雅关闭日志系统
Sync() 刷新缓冲区
Get() 获取底层 zap.Logger

Context 字段自动提取

字段 来源 说明
request_id ContextKeyRequestID 请求唯一标识
trace_id OpenTelemetry 链路追踪 ID
span_id OpenTelemetry 当前 span ID
caller_func WithCallerFunc() 调用者方法名

并发安全

所有 goroutine 调用路径:

  InfoWithCtx(ctx, "msg")
    → getDefaultLogger()
      → checkNil()                          ← initOnce.Do 保证只执行一次
      → return defaultCallerLoggerPtr.Load()  ← 原子读取全局唯一实例
  • sync.Once 保护兜底初始化
  • atomic.Pointer 发布默认 logger 与钩子快照:Init 写侧 Store、日志读侧 Load, 使「运行期重复 Init 与并发日志」不再构成内存模型层面的数据竞争
  • atomic.Int32/Int64 保护计数器
  • sync.RWMutex 保护路由器 map
  • 全程 2 个 logger 实例,不随请求增长

Init 启动期单次调用约定:虽然各包级变量已原子化,但 Init 内多次 Store 并非单一原子事务, 理论上可观察到「钩子已更新而默认 logger 尚未发布」的中间态。请在服务启动、开始处理流量之前完成 Init, 不要在流量期反复调用。

内存模型

启动时: Init() → 创建全局实例(固定)
   ↓
运行期: 每次日志调用 → 临时 []Field → GC 回收(恒定)
         SLS Producer 缓冲 → 有界(512MB 上限)
         路由器 map → 固定大小
   ↓
关闭时: Shutdown() → flush 所有缓冲 → 释放资源

内存不会持续上涨,每次调用产生的临时对象在 GC 正常回收范围内。

Benchmark 参考

不提供固定参考值:旧表既无测量机器/Go 版本/benchtime,历史 BenchmarkHighConcurrency 还存在 b.N/concurrency 假基准(现已改 b.RunParallel)。 真实数据请以目标环境实测为准:go test -bench=. -benchtime=1s -count=5。 纯 CPU 基准已使用丢弃输出(WithNoPrint(true))隔离磁盘 IO;含文件/网络 IO 的基准(BenchmarkSLSHook 等)在未配置 SLS 凭据时会自动 Skip。

集成测试:TestSLSIntegration/TestMixedLogging 会创建真实 SLS Producer(网络 IO),已收敛到 //go:build integration; 默认 go test ./pkg/logger/ 为纯本地(CPU/内存)测试。跑集成用例:go test -tags integration ./pkg/logger/。

目录结构

pkg/logger/
├── logger.go           # 核心初始化、单例管理、build 辅助
├── method.go           # 日志方法、Shutdown、Closer、Metrics
├── metrics.go          # Prometheus Collector 集成
├── option.go           # 配置选项(Functional Options 模式)
├── type.go             # Field 类型封装
├── router.go           # 日志路由、Context 字段提取
├── sls_hook.go         # 阿里云 SLS Hook 实现
├── grpcLogger.go       # gRPC 日志桥接
├── main_test.go        # 包级测试入口 TestMain(基准模式条件清理)+ isBenchmarkRun/cleanupBenchmarkFiles
├── benchmark_test.go   # 性能基准测试(纯 CPU 基准用 WithNoPrint 丢盘;路由写入基准含文件 IO 已在注释标注)
├── method_ctx_test.go  # 功能测试(含 table-driven)
├── caller_ext_test.go  # 外部测试包 logger_test:验证钩子 caller 定位到用户调用点(两条路径)
├── sls_integration_test.go # `//go:build integration`:TestSLSIntegration/TestMixedLogging(创真实 Producer、含网络 IO)
├── testutil_test.go    # 测试公共工具(getEnv)
├── grpcLogger_test.go  # grpcLogger.V 语义回归
├── sls_hook_test.go    # SLS 纯函数单测 + Fuzz(validateSLSConfig/slsFieldValue 等)
├── router_test.go      # 路由/Context 纯函数单测(mergeRouteConfig/extractContextFields 等)
├── option_test.go      # Option 校验分支单测(WithLevel/WithFormat/值域防护)
├── CHANGELOG.md        # 版本变更日志(含 SLS 浮点序列化 Bug、级别门控、caller 定位的修复记录)
└── logs/               # 日志输出目录
    ├── order/
    └── payment/

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 等链路追踪信息

func ErrorWithCtx added in v1.4.22

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

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

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

FatalWithCtx fatal 级别日志(必须提供 context)

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)

func Init

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

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

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

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

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

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

func ReplaceGRPCLoggerV2(l *zap.Logger)

ReplaceGRPCLoggerV2 替换 gRPC 默认日志记录器为 zap 实现

func RouterSync added in v1.4.22

func RouterSync() error

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

func Shutdown added in v1.4.52

func Shutdown(_ context.Context) error

Shutdown 优雅关闭日志系统,确保所有缓冲数据写入完成 关闭顺序: 已注册的 Closer → 路由器 → 默认 logger 推荐在应用 main 函数的 defer 中调用:

defer logger.Shutdown(context.Background())

func Sync

func Sync() error

Sync 刷新所有缓冲的日志条目,应用退出前应调用此方法确保日志完整写入

func WarnWithCtx added in v1.4.22

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

WarnWithCtx 警告级别日志(必须提供 context)

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

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

CustomHook 自定义钩子函数,可访问日志级别、消息和字段

type CustomHookWithCtx added in v1.4.22

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

CustomHookWithCtx 带 Context 的自定义钩子函数,可访问上下文、日志级别、消息和字段 钩子可从 context 中提取 request_id、trace_id 等链路追踪信息

type Field

type Field = zapcore.Field

Field 日志字段类型

func Any

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

Any 创建任意类型字段,适用于对象、切片、映射等复合类型 为了更好的性能和可读性,优先使用具体的类型函数

func Bool

func Bool(key string, val bool) Field

Bool 创建布尔类型字段

func Duration

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

Duration 创建时间间隔类型字段

func Err

func Err(err error) Field

Err 创建错误类型字段,err 为 nil 时自动跳过

func Float64

func Float64(key string, val float64) Field

Float64 创建浮点数类型字段

func Int

func Int(key string, val int) Field

Int 创建整数类型字段

func Int32 added in v1.0.5

func Int32(key string, val int32) Field

Int32 创建 Int32 类型字段

func Int64

func Int64(key string, val int64) Field

Int64 创建 Int64 类型字段

func Skip added in v1.4.22

func Skip() Field

Skip 跳过该字段

func String

func String(key string, val string) Field

String 创建字符串类型字段

func Stringer

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

Stringer 创建 Stringer 类型字段

func Time

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

Time 创建时间类型字段

func Uint

func Uint(key string, val uint) Field

Uint 创建无符号整数类型字段

func Uint32 added in v1.0.5

func Uint32(key string, val uint32) Field

Uint32 创建 Uint32 类型字段

func Uint64

func Uint64(key string, val uint64) Field

Uint64 创建 Uint64 类型字段

func Uintptr

func Uintptr(key string, val uintptr) Field

Uintptr 创建指针大小整数类型字段

type FileOption

type FileOption func(*fileOptions)

FileOption 文件配置选项函数类型

func WithFileIsCompression

func WithFileIsCompression(isCompression bool) FileOption

WithFileIsCompression 设置是否压缩日志文件

func WithFileMaxAge

func WithFileMaxAge(maxAge int) FileOption

WithFileMaxAge 设置旧文件最大保留天数

func WithFileMaxBackups

func WithFileMaxBackups(maxBackups int) FileOption

WithFileMaxBackups 设置旧文件最大保留数量

func WithFileMaxSize

func WithFileMaxSize(maxSize int) FileOption

WithFileMaxSize 设置日志文件最大大小(MB)

func WithFileName

func WithFileName(filename string) FileOption

WithFileName 设置日志文件名

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

func (r *LogRouter) Close() error

Close 关闭所有日志记录器并同步缓冲

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

func WithAsync(enabled bool) Option

WithAsync 启用异步日志

func WithAsyncBufferSize added in v1.4.3

func WithAsyncBufferSize(size int) Option

WithAsyncBufferSize 设置异步日志缓冲区大小(字节)

func WithAsyncFlushInterval added in v1.4.3

func WithAsyncFlushInterval(interval time.Duration) Option

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 WithFormat

func WithFormat(format string) Option

WithFormat 设置输出日志格式,console 或 json

func WithHooks

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

WithHooks 设置日志钩子

func WithLevel

func WithLevel(levelName string) Option

WithLevel 设置日志级别

func WithRoutes added in v1.4.22

func WithRoutes(routes []*RouteConfig) Option

WithRoutes 设置日志路由配置

func WithSave

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

WithSave 设置是否保存日志到文件

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

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(_ context.Context, entry zapcore.Entry, fields []Field) error

Hook 实现 CustomHookWithCtx 接口,将日志发送到阿里云 SLS

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