Documentation
¶
Overview ¶
Package slog provides a high-performance, feature-rich structured logging library for Go, extending the standard log/slog package.
Built on Go 1.23+'s official log/slog, slog adds enterprise-grade features: DLP data desensitization (36 sensitive types), tiered object pools, log subscription with backpressure control, modular extensions, and runtime dynamic switches.
Installation ¶
go get github.com/feymanlee/slog@latest
Quick Start ¶
logger := slog.Default()
logger.Info("服务启动", "port", 8080, "env", "production")
Log Levels ¶
Six levels from lowest to highest:
LevelTrace = -8 // Most detailed LevelDebug = -4 LevelInfo = 0 // Default LevelWarn = 4 LevelError = 8 LevelFatal = 12 // Calls os.Exit(1)
Set levels globally:
slog.SetLevelDebug()
slog.SetLevel("info")
slog.SetLevel(slog.LevelWarn)
Creating Loggers ¶
Builder pattern (recommended):
logger := slog.NewLoggerBuilder().
WithModule("order-service").
WithGroup("http").
EnableJSON(true).
EnableDLP(true).
Build()
Direct creation:
logger := slog.NewLoggerWithConfig(os.Stdout, &slog.Config{
EnableText: boolPtr(true),
EnableJSON: boolPtr(true),
NoColor: true,
})
Output format variants:
logger := slog.NewLoggerBuilder().UseLogfmt().Build() // Loki / Vector logger := slog.NewLoggerBuilder().UseGELF(nil).Build() // Graylog logger := slog.NewLoggerBuilder().UseNetOutput(opts).Build() // TCP/UDP
DLP Data Desensitization ¶
Enable globally:
slog.EnableDLPLogger()
Engine-level usage:
engine := dlp.NewDlpEngine()
engine.Enable()
masked := engine.DesensitizeText("手机号:13812345678") // → 手机号:138****5678
Struct tag desensitization:
type User struct {
Name string `dlp:"chinese_name"`
Phone string `dlp:"mobile_phone"`
Email string `dlp:"email"`
}
Matcher management:
engine.DisableMatchers("ipv4", "ipv6") // Disable (variadic)
engine.EnableMatchers("ipv4") // Re-enable
engine.SetMatcherEnabled("email", false) // Toggle single
engine.EnabledMatchers() // List all enabled
Supported types: chinese_name, id_card, mobile_phone, email, bank_card, ipv4, ipv6, mac, url, domain, jwt, uuid, md5, sha256, plate, vin, imei, license_plate, postal_code, address, password, username, api_key, access_token, passport, social_security, credit_card, iban, swift, lat_lng, medical_id, company_id, git_repo, device_id.
Runtime Control ¶
snapshot := slog.GetRuntimeSnapshot()
slog.ApplyRuntimeOption("level", "warn")
slog.ApplyRuntimeOption("json", "on")
slog.ApplyRuntimeOption("dlp", "on")
Subscription ¶
ch, cancel := slog.Subscribe(1000)
defer cancel()
ch, cancel = slog.SubscribeWithOptions(slog.SubscribeOptions{
BufferSize: 1000,
Backpressure: slog.SubscriptionDropOldest, // DropOldest / DropNewest / BlockWithTimeout
})
Context Propagation ¶
slog.SetContextPropagator(func(ctx context.Context) []slog.Attr {
if v, ok := ctx.Value("trace_id").(string); ok {
return []slog.Attr{slog.String("trace_id", v)}
}
return nil
})
Thread Safety ¶
All operations are goroutine-safe. Logger instances can be freely shared.
Performance ¶
Run benchmarks on the target Go version and hardware:
go test -run '^$' -bench . -benchmem ./...
For more information, see https://pkg.go.dev/github.com/feymanlee/slog
Index ¶
- Constants
- Variables
- func ConfigureRecordLimiter(ratePerSecond, burst int)
- func Countdown(msg string, seconds int)
- func Debug(msg string, args ...any)
- func DebugContext(ctx context.Context, msg string, args ...any)
- func Debugf(format string, args ...any)
- func DebugfContext(ctx context.Context, format string, args ...any)
- func DefaultCallerSkipPrefixes() []string
- func DisableDLPLogger()
- func DisableJSONLogger()
- func DisableTextLogger()
- func EnableDLPLogger()
- func EnableDiagnosticsLogging(on bool, writer ...io.Writer)
- func EnableJSONLogger()
- func EnableTextLogger()
- func Error(msg string, args ...any)
- func ErrorContext(ctx context.Context, msg string, args ...any)
- func Errorf(format string, args ...any)
- func ErrorfContext(ctx context.Context, format string, args ...any)
- func Fatal(msg string, args ...any)
- func Fatalf(format string, args ...any)
- func GetErrorComponent(err error) string
- func GetErrorOperation(err error) string
- func Info(msg string, args ...any)
- func InfoContext(ctx context.Context, msg string, args ...any)
- func Infof(format string, args ...any)
- func InfofContext(ctx context.Context, format string, args ...any)
- func IsDLPEnabled() bool
- func IsErrorType(err error, errorType ErrorType) bool
- func ListFormatters() []string
- func Loading(msg string, seconds int)
- func NewLogLogger(h Handler, level Level) *log.Logger
- func NewWriter(filename ...string) *writer
- func Printf(format string, args ...any)
- func Println(msg string, args ...any)
- func Progress(msg string, durationMs int)
- func RegisterCallerSkipPrefix(prefix string)
- func RegisterDefaultCallerSkipPrefixes()
- func RegisterFormatter(name string, fn FormatterFunc) string
- func RegisteredModules() []string
- func RemoveFormatter(id string) bool
- func ResetCallerSkipPrefixes(prefixes ...string)
- func SetAttrFormatterOrder(order ...AttrFormatterRule)
- func SetContextPropagator(fn ContextPropagatorFunc)
- func SetDefault(logger any)
- func SetLevel(level any) error
- func SetLevelDebug()
- func SetLevelError()
- func SetLevelFatal()
- func SetLevelInfo()
- func SetLevelTrace()
- func SetLevelWarn()
- func SetRecordRouter(router RecordRouter)
- func SetTimeFormat(format string)
- func Subscribe(size uint16) (<-chan SubscriptionEvent, context.CancelFunc)
- func SubscribeWithOptions(options SubscribeOptions) (<-chan SubscriptionEvent, context.CancelFunc)
- func Trace(msg string, args ...any)
- func TraceContext(ctx context.Context, msg string, args ...any)
- func Tracef(format string, args ...any)
- func TracefContext(ctx context.Context, format string, args ...any)
- func UpdateModuleConfig(name string, config modules.Config) error
- func UseModuleWithError(module modules.Module) error
- func Warn(msg string, args ...any)
- func WarnContext(ctx context.Context, msg string, args ...any)
- func Warnf(format string, args ...any)
- func WarnfContext(ctx context.Context, format string, args ...any)
- type Attr
- func Any(key string, v any) Attr
- func Bool(key string, v bool) Attr
- func Duration(key string, v time.Duration) Attr
- func Float64(key string, v float64) Attr
- func Group(key string, args ...any) Attr
- func GroupAttrs(key string, attrs ...Attr) Attr
- func Int(key string, v int) Attr
- func Int64(key string, v int64) Attr
- func String(key string, v string) Attr
- func Time(key string, v time.Time) Attr
- func Uint64(key string, v uint64) Attr
- type AttrFormatterRule
- type Config
- type ContextPropagatorFunc
- type ErrorType
- type Fields
- type FormatterFunc
- type GlobalConfig
- type Handler
- type HandlerOptions
- type JSONHandler
- type Kind
- type Level
- type LevelVar
- type Leveler
- type LogValuer
- type Logger
- func Default(modules ...string) *Logger
- func GetGlobalLogger() *Logger
- func NewGELFLogger(w io.Writer, opts *HandlerOptions, gopts *gelfmod.Options) *Logger
- func NewLogfmtLogger(w io.Writer, opts *HandlerOptions) *Logger
- func NewLogger(w io.Writer, noColor, addSource bool) *Logger
- func NewLoggerWithConfig(w io.Writer, config *Config) *Logger
- func ResetGlobalLogger(w io.Writer, noColor, addSource bool) *Logger
- func UseModule(module modules.Module) *Logger
- func With(args ...any) *Logger
- func WithGroup(name string) *Logger
- func WithValue(key string, val any) *Logger
- func (l *Logger) Countdown(msg string, seconds int, writer ...io.Writer)
- func (l *Logger) Debug(msg string, args ...any)
- func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Debugf(format string, args ...any)
- func (l *Logger) DebugfContext(ctx context.Context, format string, args ...any)
- func (l *Logger) Diagnostics() []ModuleDiagnostics
- func (l *Logger) Enabled(ctx context.Context, level Level) bool
- func (l *Logger) Error(msg string, args ...any)
- func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Errorf(format string, args ...any)
- func (l *Logger) ErrorfContext(ctx context.Context, format string, args ...any)
- func (l *Logger) Fatal(msg string, args ...any)
- func (l *Logger) FatalContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Fatalf(format string, args ...any)
- func (l *Logger) FatalfContext(ctx context.Context, format string, args ...any)
- func (l *Logger) GetLevel() Level
- func (l *Logger) GetSlogLogger() *SlogLogger
- func (l *Logger) Handler() Handler
- func (l *Logger) Info(msg string, args ...any)
- func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Infof(format string, args ...any)
- func (l *Logger) InfofContext(ctx context.Context, format string, args ...any)
- func (l *Logger) Loading(msg string, seconds int, writer ...io.Writer)
- func (l *Logger) Log(ctx context.Context, level Level, msg string, args ...any)
- func (l *Logger) LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)
- func (l *Logger) Printf(format string, args ...any)
- func (l *Logger) Println(msg string, args ...any)
- func (l *Logger) Progress(msg string, durationMs int, writer ...io.Writer)
- func (l *Logger) SetLevel(level any) *Logger
- func (l *Logger) Trace(msg string, args ...any)
- func (l *Logger) TraceContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Tracef(format string, args ...any)
- func (l *Logger) TracefContext(ctx context.Context, format string, args ...any)
- func (l *Logger) UpdateModuleConfig(name string, config modules.Config) error
- func (l *Logger) Use(module modules.Module) *Logger
- func (l *Logger) UseWithError(module modules.Module) error
- func (l *Logger) Warn(msg string, args ...any)
- func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Warnf(format string, args ...any)
- func (l *Logger) WarnfContext(ctx context.Context, format string, args ...any)
- func (l *Logger) With(args ...any) *Logger
- func (l *Logger) WithContext(ctx context.Context) *Logger
- func (l *Logger) WithDeadline(d time.Time) (*Logger, context.CancelFunc)
- func (l *Logger) WithGroup(name string) *Logger
- func (l *Logger) WithModules(modules ...modules.Module) *Logger
- func (l *Logger) WithTimeout(timeout time.Duration) (*Logger, context.CancelFunc)
- func (l *Logger) WithValue(key string, val any) *Logger
- type LoggerBuilder
- func (b *LoggerBuilder) Build() *Logger
- func (b *LoggerBuilder) EnableDLP(on bool) *LoggerBuilder
- func (b *LoggerBuilder) EnableJSON(on bool) *LoggerBuilder
- func (b *LoggerBuilder) EnableText(on bool) *LoggerBuilder
- func (b *LoggerBuilder) UseGELF(opts *gelfmod.Options) *LoggerBuilder
- func (b *LoggerBuilder) UseLogfmt() *LoggerBuilder
- func (b *LoggerBuilder) UseNetOutput(opts *outputnet.SenderOption) *LoggerBuilder
- func (b *LoggerBuilder) WithAttrs(attrs ...Attr) *LoggerBuilder
- func (b *LoggerBuilder) WithConfig(cfg *Config) *LoggerBuilder
- func (b *LoggerBuilder) WithGroup(name string) *LoggerBuilder
- func (b *LoggerBuilder) WithModule(name string) *LoggerBuilder
- func (b *LoggerBuilder) WithWriter(w io.Writer) *LoggerBuilder
- type LoggerManager
- func (lm *LoggerManager) Configure(config *GlobalConfig) error
- func (lm *LoggerManager) GetDefault() *Logger
- func (lm *LoggerManager) GetNamed(name string) *Logger
- func (lm *LoggerManager) GetStats() ManagerStats
- func (lm *LoggerManager) ListInstances() []string
- func (lm *LoggerManager) Reset()
- func (lm *LoggerManager) Shutdown()
- type ManagerStats
- type ModuleDiagnostics
- type MultiHandler
- type Record
- type RecordRouter
- type RuntimeSnapshot
- type SlogError
- func NewConfigurationError(component, field string, cause error) *SlogError
- func NewDLPError(operation, field string, cause error) *SlogError
- func NewFormatterError(operation string, cause error) *SlogError
- func NewInitializationError(component, operation string, cause error) *SlogError
- func NewInternalError(component, operation string, cause error) *SlogError
- func NewInvalidInputError(field, expected, actual string) *SlogError
- func NewModuleError(moduleName, operation string, cause error) *SlogError
- func NewProcessingError(component, operation string, cause error) *SlogError
- type SlogLogger
- type Source
- type StdLogger
- type SubscribeOptions
- type SubscriberStats
- type SubscriptionBackpressurePolicy
- type SubscriptionEvent
- type SubscriptionStats
- type TextHandler
- type Value
- func AnyValue(v any) Value
- func BoolValue(v bool) Value
- func DurationValue(v time.Duration) Value
- func Float64Value(v float64) Value
- func GroupValue(args ...Attr) Value
- func Int64Value(v int64) Value
- func IntValue(v int) Value
- func StringValue(value string) Value
- func TimeValue(v time.Time) Value
- func Uint64Value(v uint64) Value
Constants ¶
const ( // TimeKey 是标准 slog 内置时间字段名。 TimeKey = stdslog.TimeKey // LevelKey 是标准 slog 内置级别字段名。 LevelKey = stdslog.LevelKey // MessageKey 是标准 slog 内置消息字段名。 MessageKey = stdslog.MessageKey // SourceKey 是标准 slog 内置调用源字段名。 SourceKey = stdslog.SourceKey )
const ( // KindAny 表示任意 Go 值。 KindAny = stdslog.KindAny // KindBool 表示 bool 值。 KindBool = stdslog.KindBool // KindDuration 表示 time.Duration 值。 KindDuration = stdslog.KindDuration // KindFloat64 表示 float64 值。 KindFloat64 = stdslog.KindFloat64 // KindInt64 表示 int64 值。 KindInt64 = stdslog.KindInt64 // KindString 表示 string 值。 KindString = stdslog.KindString // KindTime 表示 time.Time 值。 KindTime = stdslog.KindTime // KindUint64 表示 uint64 值。 KindUint64 = stdslog.KindUint64 // KindGroup 表示属性组。 KindGroup = stdslog.KindGroup // KindLogValuer 表示延迟求值的 LogValuer。 KindLogValuer = stdslog.KindLogValuer )
const ( Name = "feymanlee/slog" Version = "v1.0.0" )
Variables ¶
var (
TimeFormat = "2006/01/02 15:04.05.000" // 默认时间格式
)
Functions ¶
func ConfigureRecordLimiter ¶
func ConfigureRecordLimiter(ratePerSecond, burst int)
ConfigureRecordLimiter 设置全局日志速率限制(ratePerSecond<=0 关闭限制)。
func DebugContext ¶
DebugContext 记录全局 Debug 日志并传播上下文。
func DebugfContext ¶
DebugfContext 记录格式化 Debug 日志并传播上下文。
func DefaultCallerSkipPrefixes ¶
func DefaultCallerSkipPrefixes() []string
DefaultCallerSkipPrefixes 返回默认建议跳过的调用栈前缀,供上层按需复用。 仅包含 slog 自己稳定暴露的 wrapper 入口,避免对具体仓库结构或源码路径产生耦合。
func EnableDiagnosticsLogging ¶
EnableDiagnosticsLogging 控制扩展管线的调试输出,可选自定义输出目标。
func ErrorContext ¶
ErrorContext 记录全局 Error 日志并传播上下文。
func ErrorfContext ¶
ErrorfContext 记录格式化 Error 日志并传播上下文。
func InfoContext ¶
InfoContext 记录全局 Info 日志并传播上下文。
func InfofContext ¶
InfofContext 记录格式化 Info 日志并传播上下文。
func NewLogLogger ¶
NewLogLogger 映射标准库 log/slog.NewLogLogger。
func NewWriter ¶
func NewWriter(filename ...string) *writer
NewWriter 创建一个新的日志写入器,支持指定一个或多个文件路径,多个路径时使用第一个有效路径 filename: 日志文件路径 默认配置:
- 单个文件最大 100MB
- 保留最近 30 天的日志
- 最多保留 30 个备份文件
- 使用本地时间
- 压缩旧文件
func RegisterCallerSkipPrefix ¶
func RegisterCallerSkipPrefix(prefix string)
RegisterCallerSkipPrefix 注册需要跳过的调用栈前缀,供外部 wrapper 透传真实业务 source。
func RegisterDefaultCallerSkipPrefixes ¶
func RegisterDefaultCallerSkipPrefixes()
RegisterDefaultCallerSkipPrefixes 注册 slog 默认 wrapper 前缀。
func RegisterFormatter ¶
func RegisterFormatter(name string, fn FormatterFunc) string
RegisterFormatter 在运行时注册新的格式化函数,返回可用于移除的 ID。
func ResetCallerSkipPrefixes ¶
func ResetCallerSkipPrefixes(prefixes ...string)
ResetCallerSkipPrefixes 重置调用栈跳过前缀,便于测试或上层完全自定义。
func SetAttrFormatterOrder ¶
func SetAttrFormatterOrder(order ...AttrFormatterRule)
SetAttrFormatterOrder 允许自定义内置属性格式化规则顺序,传入空列表时会恢复默认顺序。
func SetContextPropagator ¶
func SetContextPropagator(fn ContextPropagatorFunc)
SetContextPropagator 设置全局上下文传播方法。
func SetDefault ¶
func SetDefault(logger any)
SetDefault 设置默认 Logger,并同步标准 log/slog 与本包顶层日志入口。
logger 支持 *SlogLogger 与本包增强 *Logger,便于兼容标准库示例和 feymanlee/slog 的增强入口。
func SetLevel ¶
SetLevel 动态更新日志级别 level 可以是数字(-8, -4, 0, 4, 8, 12)或字符串(trace, debug, info, warn, error, fatal)
func SetTimeFormat ¶
func SetTimeFormat(format string)
SetTimeFormat 全局方法:设置日志时间格式
- format: 时间格式字符串,例如 "2006-01-02 15:04:05.000"
func Subscribe ¶
func Subscribe(size uint16) (<-chan SubscriptionEvent, context.CancelFunc)
Subscribe 订阅日志记录 创建一个新的日志订阅,返回接收日志记录的通道和取消订阅的函数
参数:
- size: 通道缓冲区大小,决定可以在不阻塞的情况下缓存多少日志记录
返回值:
- <-chan SubscriptionEvent: 只读的订阅事件通道,包含结构化视图和当前激活输出对应的最终渲染结果
- context.CancelFunc: 取消订阅的函数,调用后会停止接收日志并清理资源
func SubscribeWithOptions ¶
func SubscribeWithOptions(options SubscribeOptions) (<-chan SubscriptionEvent, context.CancelFunc)
SubscribeWithOptions 使用可配置背压策略订阅日志记录。 订阅者拿到的是统一发布视图,而不是原始未处理的内部 record。
func TraceContext ¶
TraceContext 记录全局 Trace 日志并传播上下文。
func TracefContext ¶
TracefContext 记录格式化 Trace 日志并传播上下文。
func UpdateModuleConfig ¶
UpdateModuleConfig 热更新默认 Logger 中已注册模块的配置。
func UseModuleWithError ¶
UseModuleWithError 全局注册模块,并返回注册错误,便于第三方模块接入时显式处理失败。
func WarnContext ¶
WarnContext 记录全局 Warn 日志并传播上下文。
Types ¶
type Attr ¶
Attr 映射标准库 log/slog.Attr。
func GroupAttrs ¶
GroupAttrs 用已有 Attr 构造分组,等价于标准库较新版本的 log/slog.GroupAttrs。
type AttrFormatterRule ¶
type AttrFormatterRule int
const ( AttrFormatterRuleSource AttrFormatterRule = iota AttrFormatterRuleLevel AttrFormatterRuleTime )
type Config ¶
type Config struct {
// 缓存配置
MaxFormatCacheSize int64 // 最大格式缓存大小
// 性能配置
StringBuilderPoolSize int // 字符串构建器池大小
// 错误处理配置
LogInternalErrors bool // 是否记录内部错误
// 输出配置
EnableText *bool // 启用文本输出(nil 表示继承全局设置)
EnableJSON *bool // 启用JSON输出(nil 表示继承全局设置)
NoColor bool // 禁用颜色
AddSource bool // 添加源代码位置
// 时间配置
TimeFormat string // 时间格式
}
Config 日志配置结构体
func (*Config) InheritJSONOutput ¶
func (c *Config) InheritJSONOutput()
InheritJSONOutput 使实例 JSON 输出沿用全局设置
func (*Config) InheritTextOutput ¶
func (c *Config) InheritTextOutput()
InheritTextOutput 使实例文本输出沿用全局设置
func (*Config) SetEnableJSON ¶
SetEnableJSON 显式设置 JSON 输出开关
func (*Config) SetEnableText ¶
SetEnableText 显式设置文本输出开关
type ContextPropagatorFunc ¶
ContextPropagatorFunc 将自定义上下文信息转换成 slog.Attr。
type FormatterFunc ¶
FormatterFunc 内部格式化器接口,避免直接依赖formatter包
type GlobalConfig ¶
type GlobalConfig struct {
DefaultWriter io.Writer
DefaultLevel Level
DefaultNoColor bool
DefaultSource bool
EnableText bool
EnableJSON bool
}
GlobalConfig 全局配置,与实例配置分离
type Handler ¶
Handler 映射标准库 log/slog.Handler。
var DiscardHandler Handler = discardHandler{}
DiscardHandler 丢弃所有日志输出。
func ApplyModulesToHandler ¶
ApplyModulesToHandler 将模块处理器应用到基础处理器上。
func NewConsoleHandler ¶
func NewConsoleHandler(w io.Writer, noColor bool, opts *HandlerOptions) Handler
NewConsoleHandler returns a log/slog.Handler using the receiver's options. Default options are used if opts is nil.
type HandlerOptions ¶
type HandlerOptions = stdslog.HandlerOptions
HandlerOptions 映射标准库 log/slog.HandlerOptions。
type JSONHandler ¶
type JSONHandler = stdslog.JSONHandler
JSONHandler 映射标准库 log/slog.JSONHandler。
func NewJSONHandler ¶
func NewJSONHandler(w io.Writer, opts *HandlerOptions) *JSONHandler
NewJSONHandler 映射标准库 log/slog.NewJSONHandler。
type Level ¶
Level 映射标准库 log/slog.Level。
func SetLogLoggerLevel ¶
SetLogLoggerLevel 映射标准库 log/slog.SetLogLoggerLevel。
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger 结构体定义,实现日志记录功能
func NewGELFLogger ¶
NewGELFLogger 使用 GELF handler 创建 Logger,面向 Graylog/Logstash。
func NewLogfmtLogger ¶
func NewLogfmtLogger(w io.Writer, opts *HandlerOptions) *Logger
NewLogfmtLogger 使用 logfmt handler 创建 Logger,便于直接接入 Loki/Vector。
func NewLoggerWithConfig ¶
NewLoggerWithConfig 使用配置创建新的日志记录器
func ResetGlobalLogger ¶
ResetGlobalLogger 重置全局logger实例 这在某些情况下很有用,比如需要更改全局logger的输出目标
func (*Logger) DebugContext ¶
DebugContext 记录 Debug 级别日志,附带上下文传播。
func (*Logger) DebugfContext ¶
DebugfContext 记录格式化调试日志,附带上下文传播。
func (*Logger) Diagnostics ¶
func (l *Logger) Diagnostics() []ModuleDiagnostics
Diagnostics 返回模块健康与指标快照。
func (*Logger) ErrorContext ¶
ErrorContext 记录错误级别日志,附带上下文传播。
func (*Logger) ErrorfContext ¶
ErrorfContext 记录格式化的错误日志,附带上下文传播。
func (*Logger) FatalContext ¶
FatalContext 记录致命日志并退出,附带上下文传播。
func (*Logger) FatalfContext ¶
FatalfContext 记录格式化致命日志并退出,附带上下文传播。
func (*Logger) InfoContext ¶
InfoContext 记录信息级别日志,附带上下文传播。
func (*Logger) InfofContext ¶
InfofContext 记录格式化的信息日志,附带上下文传播。
func (*Logger) TraceContext ¶
TraceContext 记录跟踪日志,附带上下文传播。
func (*Logger) TracefContext ¶
TracefContext 记录格式化的 Trace 日志,附带上下文传播。
func (*Logger) UpdateModuleConfig ¶
UpdateModuleConfig 热更新当前 Logger Lineage 中已注册模块的配置。
func (*Logger) UseWithError ¶
UseWithError 为 Logger 添加模块实例,并向调用方返回注册错误。
func (*Logger) WarnContext ¶
WarnContext 记录警告级别日志,附带上下文传播。
func (*Logger) WarnfContext ¶
WarnfContext 记录格式化的警告日志,附带上下文传播。
func (*Logger) WithContext ¶
WithContext 创建带有上下文的新Logger
func (*Logger) WithDeadline ¶
WithDeadline 创建带截止时间的Logger
func (*Logger) WithModules ¶
WithModules 便捷添加多个模块。
func (*Logger) WithTimeout ¶
WithTimeout 创建带超时的Logger
type LoggerBuilder ¶
type LoggerBuilder struct {
// contains filtered or unexported fields
}
LoggerBuilder 通过链式方式快速构建 Logger,便于上层按需开启 Text/JSON/DLP、预置分组与字段。
func NewLoggerBuilder ¶
func NewLoggerBuilder() *LoggerBuilder
NewLoggerBuilder 创建一个新的构建器,默认输出到 stdout、启用文本日志。
func (*LoggerBuilder) EnableDLP ¶
func (b *LoggerBuilder) EnableDLP(on bool) *LoggerBuilder
EnableDLP 控制 DLP 脱敏能力。
func (*LoggerBuilder) EnableJSON ¶
func (b *LoggerBuilder) EnableJSON(on bool) *LoggerBuilder
EnableJSON 控制 JSON 输出。
func (*LoggerBuilder) EnableText ¶
func (b *LoggerBuilder) EnableText(on bool) *LoggerBuilder
EnableText 控制文本输出。
func (*LoggerBuilder) UseGELF ¶
func (b *LoggerBuilder) UseGELF(opts *gelfmod.Options) *LoggerBuilder
UseGELF 切换为 GELF 输出,并可附带选项。
func (*LoggerBuilder) UseLogfmt ¶
func (b *LoggerBuilder) UseLogfmt() *LoggerBuilder
UseLogfmt 切换为 logfmt 输出。
func (*LoggerBuilder) UseNetOutput ¶
func (b *LoggerBuilder) UseNetOutput(opts *outputnet.SenderOption) *LoggerBuilder
UseNetOutput 切换为通用网络输出,适用于任意 TCP/UDP 接收端。
func (*LoggerBuilder) WithAttrs ¶
func (b *LoggerBuilder) WithAttrs(attrs ...Attr) *LoggerBuilder
WithAttrs 预置结构化字段。
func (*LoggerBuilder) WithConfig ¶
func (b *LoggerBuilder) WithConfig(cfg *Config) *LoggerBuilder
WithConfig 使用自定义配置,内部会复制一份避免外部修改产生副作用。
func (*LoggerBuilder) WithGroup ¶
func (b *LoggerBuilder) WithGroup(name string) *LoggerBuilder
WithGroup 预置日志分组。
func (*LoggerBuilder) WithModule ¶
func (b *LoggerBuilder) WithModule(name string) *LoggerBuilder
WithModule 为日志添加模块字段。
func (*LoggerBuilder) WithWriter ¶
func (b *LoggerBuilder) WithWriter(w io.Writer) *LoggerBuilder
WithWriter 指定输出目标。
type LoggerManager ¶
type LoggerManager struct {
// contains filtered or unexported fields
}
LoggerManager 全局日志管理器,负责管理所有logger实例 解决全局状态混乱问题,实现实例隔离
func (*LoggerManager) Configure ¶
func (lm *LoggerManager) Configure(config *GlobalConfig) error
Configure 配置全局设置 会同步运行时全局开关,并就地更新已存在实例,避免状态分叉。
func (*LoggerManager) GetDefault ¶
func (lm *LoggerManager) GetDefault() *Logger
GetDefault 获取默认logger实例 线程安全,支持延迟初始化
func (*LoggerManager) GetNamed ¶
func (lm *LoggerManager) GetNamed(name string) *Logger
GetNamed 获取或创建命名logger实例 支持实例隔离,每个名称对应独立的logger
func (*LoggerManager) GetStats ¶
func (lm *LoggerManager) GetStats() ManagerStats
GetStats 获取管理器统计信息
func (*LoggerManager) ListInstances ¶
func (lm *LoggerManager) ListInstances() []string
ListInstances 列出所有已创建的logger实例名称
type ManagerStats ¶
Stats 返回管理器统计信息
type ModuleDiagnostics ¶
type ModuleDiagnostics struct {
Name string `json:"name"`
Type modules.ModuleType `json:"type"`
Enabled bool `json:"enabled"`
Healthy *bool `json:"healthy,omitempty"`
Metrics map[string]any `json:"metrics,omitempty"`
Priority int `json:"priority"`
}
ModuleDiagnostics 描述模块健康与指标信息。
func CollectModuleDiagnostics ¶
func CollectModuleDiagnostics() []ModuleDiagnostics
CollectModuleDiagnostics 聚合已注册模块的健康状态与指标。
type MultiHandler ¶
type MultiHandler struct {
// contains filtered or unexported fields
}
MultiHandler 将同一条记录分发给多个 Handler。
func NewMultiHandler ¶
func NewMultiHandler(handlers ...Handler) *MultiHandler
NewMultiHandler 创建 MultiHandler,并复制输入切片以避免外部突变影响。
func (*MultiHandler) Enabled ¶
func (h *MultiHandler) Enabled(ctx context.Context, level Level) bool
Enabled 判断任一子 Handler 是否会处理当前级别。
func (*MultiHandler) Handle ¶
func (h *MultiHandler) Handle(ctx context.Context, r Record) error
Handle 将记录发送给所有启用的子 Handler。
func (*MultiHandler) WithAttrs ¶
func (h *MultiHandler) WithAttrs(attrs []Attr) Handler
WithAttrs 返回带固定属性的新 MultiHandler。
func (*MultiHandler) WithGroup ¶
func (h *MultiHandler) WithGroup(name string) Handler
WithGroup 返回带分组的新 MultiHandler。
type RecordRouter ¶
RecordRouter 定义模块路由策略,返回要接收当前记录的模块名列表。
type RuntimeSnapshot ¶
type RuntimeSnapshot struct {
Level Level `json:"level"`
TextEnabled bool `json:"text_enabled"`
JSONEnabled bool `json:"json_enabled"`
DLPEnabled bool `json:"dlp_enabled"`
DLPVersion int64 `json:"dlp_version"`
Message string `json:"message,omitempty"`
}
RuntimeSnapshot 描述当前运行时开关状态,便于面板/CLI 展示。
func ApplyRuntimeOption ¶
func ApplyRuntimeOption(option, value string) (RuntimeSnapshot, error)
ApplyRuntimeOption 通过字符串选项调整全局开关,返回更新后的状态。
type SlogError ¶
type SlogError struct {
Type ErrorType
Component string
Operation string
Field string
Expected string
Actual string
Details map[string]any
Cause error
}
SlogError 结构化错误类型 提供更丰富的错误上下文信息,便于调试和错误处理
func NewConfigurationError ¶
NewConfigurationError 创建配置错误
func NewDLPError ¶
NewDLPError 创建DLP相关错误
func NewFormatterError ¶
NewFormatterError 创建格式化器相关错误
func NewInitializationError ¶
NewInitializationError 创建初始化错误
func NewInternalError ¶
NewInternalError 创建内部错误
func NewInvalidInputError ¶
NewInvalidInputError 创建输入无效错误
func NewModuleError ¶
NewModuleError 创建模块相关错误
func NewProcessingError ¶
NewProcessingError 创建处理错误
type SlogLogger ¶
SlogLogger 映射标准库 log/slog.Logger,用于避免与本包增强 Logger 重名。
func New ¶
func New(handler Handler) *SlogLogger
type SubscribeOptions ¶
type SubscribeOptions struct {
// BufferSize 订阅缓冲区大小。
BufferSize uint16
// Backpressure 背压策略;空值时默认 drop_oldest。
Backpressure SubscriptionBackpressurePolicy
// BlockTimeout 仅在 block_with_timeout 模式下生效。
BlockTimeout time.Duration
}
SubscribeOptions 订阅选项。
type SubscriberStats ¶
type SubscriberStats struct {
ID int64 `json:"id"`
State string `json:"state"`
BufferSize int `json:"buffer_size"`
QueueLen int `json:"queue_len"`
Backpressure SubscriptionBackpressurePolicy `json:"backpressure"`
BlockTimeout time.Duration `json:"block_timeout"`
CreatedAt time.Time `json:"created_at"`
Published uint64 `json:"published"`
Delivered uint64 `json:"delivered"`
Dropped uint64 `json:"dropped"`
DroppedOldest uint64 `json:"dropped_oldest"`
DroppedNewest uint64 `json:"dropped_newest"`
DroppedTimed uint64 `json:"dropped_timed_out"`
HighWatermark uint64 `json:"high_watermark"`
}
SubscriberStats 描述单个订阅者运行状态与背压统计。
func GetSubscriberStats ¶
func GetSubscriberStats(id int64) (SubscriberStats, bool)
GetSubscriberStats 根据订阅ID返回统计快照。
func ListSubscriberStats ¶
func ListSubscriberStats() []SubscriberStats
ListSubscriberStats 返回所有订阅者统计快照(按订阅ID升序)。
type SubscriptionBackpressurePolicy ¶
type SubscriptionBackpressurePolicy string
SubscriptionBackpressurePolicy 定义订阅通道在高压场景下的背压策略。
const ( // SubscriptionDropOldest 丢弃最旧消息,优先保留最新数据(默认)。 SubscriptionDropOldest SubscriptionBackpressurePolicy = "drop_oldest" // SubscriptionDropNewest 丢弃最新消息,优先保留已入队数据。 SubscriptionDropNewest SubscriptionBackpressurePolicy = "drop_newest" // SubscriptionBlockWithTimeout 在超时时间内阻塞等待可写,超时后丢弃。 SubscriptionBlockWithTimeout SubscriptionBackpressurePolicy = "block_with_timeout" )
type SubscriptionEvent ¶
type SubscriptionEvent struct {
// Record 是已应用前缀、formatter、DLP 与 context 字段后的结构化日志。
Record Record
// Rendered 是与当前激活主输出一致的最终语义化内容;若未启用任何输出则为空。
Rendered string
// Format 表示 Rendered 采用的格式,取值为 text、json 或空字符串。
Format string
}
SubscriptionEvent 描述一次统一发布后的订阅事件。 其中 Record 保留结构化视图,Rendered 则严格跟随当前激活的主输出格式。
type SubscriptionStats ¶
type SubscriptionStats struct {
Subscribers int `json:"subscribers"`
ActiveSubscribers int `json:"active_subscribers"`
ClosingSubscribers int `json:"closing_subscribers"`
ClosedSubscribers int `json:"closed_subscribers"`
Published uint64 `json:"published"`
Delivered uint64 `json:"delivered"`
Dropped uint64 `json:"dropped"`
DroppedOldest uint64 `json:"dropped_oldest"`
DroppedNewest uint64 `json:"dropped_newest"`
DroppedTimed uint64 `json:"dropped_timed_out"`
Evicted uint64 `json:"evicted"`
}
SubscriptionStats 汇总所有订阅者统计。
func GetSubscriptionStats ¶
func GetSubscriptionStats() SubscriptionStats
GetSubscriptionStats 返回订阅系统汇总统计。
type TextHandler ¶
type TextHandler = stdslog.TextHandler
TextHandler 映射标准库 log/slog.TextHandler。
func NewTextHandler ¶
func NewTextHandler(w io.Writer, opts *HandlerOptions) *TextHandler
NewTextHandler 映射标准库 log/slog.NewTextHandler。
type Value ¶
Value 映射标准库 log/slog.Value。
func DurationValue ¶
DurationValue 映射标准库 log/slog.DurationValue。