Documentation
¶
Overview ¶
Package slog provides a high-performance, feature-rich structured logging library for Go, extending the standard log/slog package.
slog is built on Go 1.23+'s official log/slog package and provides enhanced features including flexible log level control, colored output, structured logging, and data loss prevention (DLP) capabilities.
Installation ¶
go get github.com/darkit/slog@latest
Quick Start ¶
package main
import (
"os"
"github.com/darkit/slog"
)
func main() {
logger := slog.NewLogger(os.Stdout, false, false)
logger.Info("Hello Slog!")
// Structured logging
logger.Info("User logged in",
"user_id", 123,
"action", "login",
)
}
Log Levels ¶
slog supports six log levels, from lowest to highest:
LevelTrace = -8 // Most detailed LevelDebug = -4 // Debug information LevelInfo = 0 // General info (default) LevelWarn = 4 // Warnings LevelError = 8 // Errors LevelFatal = 12 // Fatal errors (exits program)
Set levels globally:
slog.SetLevelDebug()
slog.SetLevel("info")
slog.SetLevel(slog.LevelWarn)
Creating Loggers ¶
Basic creation:
logger := slog.NewLogger(os.Stdout, noColor, addSource)
With configuration:
cfg := slog.DefaultConfig() cfg.SetEnableText(true) cfg.SetEnableJSON(true) logger := slog.NewLoggerWithConfig(os.Stdout, cfg)
Builder pattern:
logger := slog.NewLoggerBuilder().
WithModule("order").
WithGroup("api").
EnableJSON(true).
Build()
Structured Logging ¶
logger.Info("Request processed",
"method", "GET",
"path", "/users",
"duration", 150*time.Millisecond,
)
Data Loss Prevention (DLP) ¶
Enable DLP to automatically desensitize sensitive data:
slog.EnableDLPLogger()
type User struct {
Name string `dlp:"chinese_name"`
Phone string `dlp:"mobile_phone"`
Email string `dlp:"email"`
}
Supported DLP types: Chinese name, ID card, phone number, email, bank card, address, password, license plate, IPv4/IPv6, JWT, URL.
File Logging ¶
writer := slog.NewWriter("logs/app.log").
SetMaxSize(100). // MB
SetMaxAge(7). // Days
SetMaxBackups(10).
SetCompress(true)
logger := slog.NewLogger(writer, false, false)
Runtime Control ¶
snapshot := slog.GetRuntimeSnapshot()
slog.ApplyRuntimeOption("level", "warn")
slog.ApplyRuntimeOption("json", "on")
Subscription ¶
Subscribe to log records for external processing:
ch, cancel := slog.Subscribe(1000)
defer cancel()
go func() {
for event := range ch {
_ = event.Record // 结构化视图
_ = event.Rendered // 当前激活输出对应的最终渲染结果
}
}()
Thread Safety ¶
All slog operations are thread-safe. Logger instances can be safely shared across goroutines. Global configuration changes are also concurrency-safe.
Performance ¶
slog is optimized for high-performance scenarios:
- Tiered buffer pools for memory reuse
- LRU cache for format string detection
- xxhash64 for cache key generation
- Atomic operations for minimal lock contention
For more information, see https://pkg.go.dev/github.com/darkit/slog
Index ¶
- Constants
- Variables
- func ApplyModulesToHandler(baseHandler slog.Handler, moduleList []modules.Module) slog.Handler
- 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 GetSlogLogger() *slog.Logger
- 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 New(handler Handler) *slog.Logger
- func NewConsoleHandler(w io.Writer, noColor bool, opts *slog.HandlerOptions) slog.Handler
- func NewJSONHandler(w io.Writer, opts *HandlerOptions) *slog.JSONHandler
- func NewOptions(options *slog.HandlerOptions) *slog.HandlerOptions
- func NewTextHandler(w io.Writer, opts *HandlerOptions) *slog.TextHandler
- 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 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 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 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 Level
- type Logger
- func Default(modules ...string) *Logger
- func GetGlobalLogger() *Logger
- func NewGELFLogger(w io.Writer, opts *slog.HandlerOptions, gopts *gelfmod.Options) *Logger
- func NewLogfmtLogger(w io.Writer, opts *slog.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) Debugf(format string, args ...any)
- func (l *Logger) DebugfContext(ctx context.Context, format string, args ...any)
- func (l *Logger) Diagnostics() []ModuleDiagnostics
- 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() *slog.Logger
- 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) 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) Use(module modules.Module) *Logger
- 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 interface{}) *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 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 SubscribeOptions
- type SubscriberStats
- type SubscriptionBackpressurePolicy
- type SubscriptionEvent
- type SubscriptionStats
- type Value
Constants ¶
const ( TimeKey = slog.TimeKey LevelKey = slog.LevelKey MessageKey = slog.MessageKey SourceKey = slog.SourceKey )
const ( Name = "darkit/slog" Version = "v0.2.0" )
Variables ¶
var (
TimeFormat = "2006/01/02 15:04.05.000" // 默认时间格式
)
Functions ¶
func ApplyModulesToHandler ¶ added in v0.1.0
ApplyModulesToHandler 将模块处理器应用到基础处理器上。
func ConfigureRecordLimiter ¶ added in v0.1.2
func ConfigureRecordLimiter(ratePerSecond, burst int)
ConfigureRecordLimiter 设置全局日志速率限制(ratePerSecond<=0 关闭限制)。
func DebugContext ¶ added in v0.1.3
DebugContext 记录全局 Debug 日志并传播上下文。
func DebugfContext ¶ added in v0.1.3
DebugfContext 记录格式化 Debug 日志并传播上下文。
func DefaultCallerSkipPrefixes ¶ added in v0.2.0
func DefaultCallerSkipPrefixes() []string
DefaultCallerSkipPrefixes 返回默认建议跳过的调用栈前缀,供上层按需复用。 仅包含 slog 自己稳定暴露的 wrapper 入口,避免对具体仓库结构或源码路径产生耦合。
func EnableDiagnosticsLogging ¶ added in v0.1.2
EnableDiagnosticsLogging 控制扩展管线的调试输出,可选自定义输出目标。
func ErrorContext ¶ added in v0.1.3
ErrorContext 记录全局 Error 日志并传播上下文。
func ErrorfContext ¶ added in v0.1.3
ErrorfContext 记录格式化 Error 日志并传播上下文。
func GetErrorComponent ¶ added in v0.1.0
GetErrorComponent 获取错误组件名称
func GetErrorOperation ¶ added in v0.1.0
GetErrorOperation 获取错误操作名称
func GetSlogLogger ¶ added in v0.0.16
GetSlogLogger 返回原始log/slog的日志记录器
func InfoContext ¶ added in v0.1.3
InfoContext 记录全局 Info 日志并传播上下文。
func InfofContext ¶ added in v0.1.3
InfofContext 记录格式化 Info 日志并传播上下文。
func IsErrorType ¶ added in v0.1.0
IsErrorType 检查错误是否为指定类型
func ListFormatters ¶ added in v0.1.2
func ListFormatters() []string
ListFormatters 返回当前激活的格式化器名称列表。
func NewConsoleHandler ¶ added in v0.0.2
NewConsoleHandler returns a log/slog.Handler using the receiver's options. Default options are used if opts is nil.
func NewJSONHandler ¶ added in v0.0.2
func NewJSONHandler(w io.Writer, opts *HandlerOptions) *slog.JSONHandler
func NewOptions ¶ added in v0.0.2
func NewOptions(options *slog.HandlerOptions) *slog.HandlerOptions
NewOptions 创建新的处理程序选项。
func NewTextHandler ¶ added in v0.0.2
func NewTextHandler(w io.Writer, opts *HandlerOptions) *slog.TextHandler
func NewWriter ¶ added in v0.0.19
func NewWriter(filename ...string) *writer
NewWriter 创建一个新的日志写入器,支持指定一个或多个文件路径,多个路径时使用第一个有效路径 filename: 日志文件路径 默认配置:
- 单个文件最大 100MB
- 保留最近 30 天的日志
- 最多保留 30 个备份文件
- 使用本地时间
- 压缩旧文件
func RegisterCallerSkipPrefix ¶ added in v0.2.0
func RegisterCallerSkipPrefix(prefix string)
RegisterCallerSkipPrefix 注册需要跳过的调用栈前缀,供外部 wrapper 透传真实业务 source。
func RegisterDefaultCallerSkipPrefixes ¶ added in v0.2.0
func RegisterDefaultCallerSkipPrefixes()
RegisterDefaultCallerSkipPrefixes 注册 slog 默认 wrapper 前缀。
func RegisterFormatter ¶ added in v0.1.2
func RegisterFormatter(name string, fn FormatterFunc) string
RegisterFormatter 在运行时注册新的格式化函数,返回可用于移除的 ID。
func RegisteredModules ¶ added in v0.1.2
func RegisteredModules() []string
RegisteredModules 返回当前已注册的模块名称。
func RemoveFormatter ¶ added in v0.1.2
RemoveFormatter 根据 ID 移除先前注册的格式化函数。
func ResetCallerSkipPrefixes ¶ added in v0.2.0
func ResetCallerSkipPrefixes(prefixes ...string)
ResetCallerSkipPrefixes 重置调用栈跳过前缀,便于测试或上层完全自定义。
func SetAttrFormatterOrder ¶ added in v0.1.2
func SetAttrFormatterOrder(order ...AttrFormatterRule)
SetAttrFormatterOrder 允许自定义内置属性格式化规则顺序,传入空列表时会恢复默认顺序。
func SetContextPropagator ¶ added in v0.1.2
func SetContextPropagator(fn ContextPropagatorFunc)
SetContextPropagator 设置全局上下文传播方法。
func SetLevel ¶ added in v0.0.23
SetLevel 动态更新日志级别 level 可以是数字(-8, -4, 0, 4, 8, 12)或字符串(trace, debug, info, warn, error, fatal)
func SetRecordRouter ¶ added in v0.1.2
func SetRecordRouter(router RecordRouter)
SetRecordRouter 自定义模块路由策略。
func SetTimeFormat ¶ added in v0.1.0
func SetTimeFormat(format string)
SetTimeFormat 全局方法:设置日志时间格式
- format: 时间格式字符串,例如 "2006-01-02 15:04:05.000"
func Subscribe ¶ added in v0.0.23
func Subscribe(size uint16) (<-chan SubscriptionEvent, context.CancelFunc)
Subscribe 订阅日志记录 创建一个新的日志订阅,返回接收日志记录的通道和取消订阅的函数
参数:
- size: 通道缓冲区大小,决定可以在不阻塞的情况下缓存多少日志记录
返回值:
- <-chan SubscriptionEvent: 只读的订阅事件通道,包含结构化视图和当前激活输出对应的最终渲染结果
- context.CancelFunc: 取消订阅的函数,调用后会停止接收日志并清理资源
func SubscribeWithOptions ¶ added in v0.2.0
func SubscribeWithOptions(options SubscribeOptions) (<-chan SubscriptionEvent, context.CancelFunc)
SubscribeWithOptions 使用可配置背压策略订阅日志记录。 订阅者拿到的是统一发布视图,而不是原始未处理的内部 record。
func TraceContext ¶ added in v0.1.3
TraceContext 记录全局 Trace 日志并传播上下文。
func TracefContext ¶ added in v0.1.3
TracefContext 记录格式化 Trace 日志并传播上下文。
func UpdateModuleConfig ¶ added in v0.1.2
UpdateModuleConfig 热更新已注册模块的配置。
func WarnContext ¶ added in v0.1.3
WarnContext 记录全局 Warn 日志并传播上下文。
Types ¶
type AttrFormatterRule ¶ added in v0.1.2
type AttrFormatterRule int
const ( AttrFormatterRuleSource AttrFormatterRule = iota AttrFormatterRuleLevel AttrFormatterRuleTime )
type Config ¶ added in v0.1.0
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 ¶ added in v0.1.0
func (c *Config) InheritJSONOutput()
InheritJSONOutput 使实例 JSON 输出沿用全局设置
func (*Config) InheritTextOutput ¶ added in v0.1.0
func (c *Config) InheritTextOutput()
InheritTextOutput 使实例文本输出沿用全局设置
func (*Config) SetEnableJSON ¶ added in v0.1.0
SetEnableJSON 显式设置 JSON 输出开关
func (*Config) SetEnableText ¶ added in v0.1.0
SetEnableText 显式设置文本输出开关
type ContextPropagatorFunc ¶ added in v0.1.2
ContextPropagatorFunc 将自定义上下文信息转换成 slog.Attr。
type Fields ¶ added in v0.0.18
type Fields struct {
// contains filtered or unexported fields
}
Fields 存储上下文字段
type FormatterFunc ¶ added in v0.1.0
FormatterFunc 内部格式化器接口,避免直接依赖formatter包
type GlobalConfig ¶ added in v0.1.0
type GlobalConfig struct {
DefaultWriter io.Writer
DefaultLevel Level
DefaultNoColor bool
DefaultSource bool
EnableText bool
EnableJSON bool
}
GlobalConfig 全局配置,与实例配置分离
type HandlerOptions ¶ added in v0.0.2
type HandlerOptions = slog.HandlerOptions
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger 结构体定义,实现日志记录功能
func GetGlobalLogger ¶ added in v0.1.0
func GetGlobalLogger() *Logger
GetGlobalLogger 返回全局 logger 实例。
func NewGELFLogger ¶ added in v0.1.3
NewGELFLogger 使用 GELF handler 创建 Logger,面向 Graylog/Logstash。
func NewLogfmtLogger ¶ added in v0.1.3
func NewLogfmtLogger(w io.Writer, opts *slog.HandlerOptions) *Logger
NewLogfmtLogger 使用 logfmt handler 创建 Logger,便于直接接入 Loki/Vector。
func NewLoggerWithConfig ¶ added in v0.1.0
NewLoggerWithConfig 使用配置创建新的日志记录器
func ResetGlobalLogger ¶ added in v0.1.0
ResetGlobalLogger 重置全局logger实例 这在某些情况下很有用,比如需要更改全局logger的输出目标
func WithGroup ¶ added in v0.0.11
WithGroup 创建一个带有指定组名的全局日志记录器 这是一个包级别的便捷方法 参数:
- name: 日志组的名称
返回:
- 带有指定组名的新日志记录器实例
func (*Logger) DebugfContext ¶ added in v0.1.3
DebugfContext 记录格式化调试日志,附带上下文传播。
func (*Logger) Diagnostics ¶ added in v0.1.2
func (l *Logger) Diagnostics() []ModuleDiagnostics
Diagnostics 返回模块健康与指标快照。
func (*Logger) ErrorContext ¶ added in v0.1.3
ErrorContext 记录错误级别日志,附带上下文传播。
func (*Logger) ErrorfContext ¶ added in v0.1.3
ErrorfContext 记录格式化的错误日志,附带上下文传播。
func (*Logger) FatalContext ¶ added in v0.1.3
FatalContext 记录致命日志并退出,附带上下文传播。
func (*Logger) FatalfContext ¶ added in v0.1.3
FatalfContext 记录格式化致命日志并退出,附带上下文传播。
func (*Logger) GetSlogLogger ¶ added in v0.0.16
GetSlogLogger 方法
func (*Logger) InfoContext ¶ added in v0.1.3
InfoContext 记录信息级别日志,附带上下文传播。
func (*Logger) InfofContext ¶ added in v0.1.3
InfofContext 记录格式化的信息日志,附带上下文传播。
func (*Logger) TraceContext ¶ added in v0.1.3
TraceContext 记录跟踪日志,附带上下文传播。
func (*Logger) TracefContext ¶ added in v0.1.3
TracefContext 记录格式化的 Trace 日志,附带上下文传播。
func (*Logger) WarnContext ¶ added in v0.1.3
WarnContext 记录警告级别日志,附带上下文传播。
func (*Logger) WarnfContext ¶ added in v0.1.3
WarnfContext 记录格式化的警告日志,附带上下文传播。
func (*Logger) WithContext ¶ added in v0.0.7
WithContext 创建带有上下文的新Logger
func (*Logger) WithDeadline ¶ added in v0.0.23
WithDeadline 创建带截止时间的Logger
func (*Logger) WithModules ¶ added in v0.1.0
WithModules 便捷添加多个模块。
func (*Logger) WithTimeout ¶ added in v0.0.23
WithTimeout 创建带超时的Logger
type LoggerBuilder ¶ added in v0.1.3
type LoggerBuilder struct {
// contains filtered or unexported fields
}
LoggerBuilder 通过链式方式快速构建 Logger,便于上层按需开启 Text/JSON/DLP、预置分组与字段。
func NewLoggerBuilder ¶ added in v0.1.3
func NewLoggerBuilder() *LoggerBuilder
NewLoggerBuilder 创建一个新的构建器,默认输出到 stdout、启用文本日志。
func (*LoggerBuilder) Build ¶ added in v0.1.3
func (b *LoggerBuilder) Build() *Logger
Build 构建 Logger 实例。
func (*LoggerBuilder) EnableDLP ¶ added in v0.1.3
func (b *LoggerBuilder) EnableDLP(on bool) *LoggerBuilder
EnableDLP 控制 DLP 脱敏能力。
func (*LoggerBuilder) EnableJSON ¶ added in v0.1.3
func (b *LoggerBuilder) EnableJSON(on bool) *LoggerBuilder
EnableJSON 控制 JSON 输出。
func (*LoggerBuilder) EnableText ¶ added in v0.1.3
func (b *LoggerBuilder) EnableText(on bool) *LoggerBuilder
EnableText 控制文本输出。
func (*LoggerBuilder) UseGELF ¶ added in v0.1.3
func (b *LoggerBuilder) UseGELF(opts *gelfmod.Options) *LoggerBuilder
UseGELF 切换为 GELF 输出,并可附带选项。
func (*LoggerBuilder) UseLogfmt ¶ added in v0.1.3
func (b *LoggerBuilder) UseLogfmt() *LoggerBuilder
UseLogfmt 切换为 logfmt 输出。
func (*LoggerBuilder) UseNetOutput ¶ added in v0.2.0
func (b *LoggerBuilder) UseNetOutput(opts *outputnet.SenderOption) *LoggerBuilder
UseNetOutput 切换为通用网络输出,适用于任意 TCP/UDP 接收端。
func (*LoggerBuilder) WithAttrs ¶ added in v0.1.3
func (b *LoggerBuilder) WithAttrs(attrs ...Attr) *LoggerBuilder
WithAttrs 预置结构化字段。
func (*LoggerBuilder) WithConfig ¶ added in v0.1.3
func (b *LoggerBuilder) WithConfig(cfg *Config) *LoggerBuilder
WithConfig 使用自定义配置,内部会复制一份避免外部修改产生副作用。
func (*LoggerBuilder) WithGroup ¶ added in v0.1.3
func (b *LoggerBuilder) WithGroup(name string) *LoggerBuilder
WithGroup 预置日志分组。
func (*LoggerBuilder) WithModule ¶ added in v0.1.3
func (b *LoggerBuilder) WithModule(name string) *LoggerBuilder
WithModule 为日志添加模块字段。
func (*LoggerBuilder) WithWriter ¶ added in v0.1.3
func (b *LoggerBuilder) WithWriter(w io.Writer) *LoggerBuilder
WithWriter 指定输出目标。
type LoggerManager ¶ added in v0.1.0
type LoggerManager struct {
// contains filtered or unexported fields
}
LoggerManager 全局日志管理器,负责管理所有logger实例 解决全局状态混乱问题,实现实例隔离
func (*LoggerManager) Configure ¶ added in v0.1.0
func (lm *LoggerManager) Configure(config *GlobalConfig) error
Configure 配置全局设置 会同步运行时全局开关,并就地更新已存在实例,避免状态分叉。
func (*LoggerManager) GetDefault ¶ added in v0.1.0
func (lm *LoggerManager) GetDefault() *Logger
GetDefault 获取默认logger实例 线程安全,支持延迟初始化
func (*LoggerManager) GetNamed ¶ added in v0.1.0
func (lm *LoggerManager) GetNamed(name string) *Logger
GetNamed 获取或创建命名logger实例 支持实例隔离,每个名称对应独立的logger
func (*LoggerManager) GetStats ¶ added in v0.1.0
func (lm *LoggerManager) GetStats() ManagerStats
GetStats 获取管理器统计信息
func (*LoggerManager) ListInstances ¶ added in v0.1.0
func (lm *LoggerManager) ListInstances() []string
ListInstances 列出所有已创建的logger实例名称
func (*LoggerManager) Reset ¶ added in v0.1.0
func (lm *LoggerManager) Reset()
Reset 重置管理器状态 清除所有实例,在测试中很有用
func (*LoggerManager) Shutdown ¶ added in v0.1.0
func (lm *LoggerManager) Shutdown()
Shutdown 关闭管理器 清理所有资源,程序退出时调用
type ManagerStats ¶ added in v0.1.0
Stats 返回管理器统计信息
type ModuleDiagnostics ¶ added in v0.1.2
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 ¶ added in v0.1.2
func CollectModuleDiagnostics() []ModuleDiagnostics
CollectModuleDiagnostics 聚合已注册模块的健康状态与指标。
type RecordRouter ¶ added in v0.1.2
RecordRouter 定义模块路由策略,返回要接收当前记录的模块名列表。
type RuntimeSnapshot ¶ added in v0.1.3
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 ¶ added in v0.1.3
func ApplyRuntimeOption(option, value string) (RuntimeSnapshot, error)
ApplyRuntimeOption 通过字符串选项调整全局开关,返回更新后的状态。
func GetRuntimeSnapshot ¶ added in v0.1.3
func GetRuntimeSnapshot() RuntimeSnapshot
GetRuntimeSnapshot 返回当前运行时状态快照。
type SlogError ¶ added in v0.1.0
type SlogError struct {
Type ErrorType
Component string
Operation string
Field string
Expected string
Actual string
Details map[string]interface{}
Cause error
}
SlogError 结构化错误类型 提供更丰富的错误上下文信息,便于调试和错误处理
func NewConfigurationError ¶ added in v0.1.0
NewConfigurationError 创建配置错误
func NewDLPError ¶ added in v0.1.0
NewDLPError 创建DLP相关错误
func NewFormatterError ¶ added in v0.1.0
NewFormatterError 创建格式化器相关错误
func NewInitializationError ¶ added in v0.1.0
NewInitializationError 创建初始化错误
func NewInternalError ¶ added in v0.1.0
NewInternalError 创建内部错误
func NewInvalidInputError ¶ added in v0.1.0
NewInvalidInputError 创建输入无效错误
func NewModuleError ¶ added in v0.1.0
NewModuleError 创建模块相关错误
func NewProcessingError ¶ added in v0.1.0
NewProcessingError 创建处理错误
func (*SlogError) GetDetails ¶ added in v0.1.0
GetDetails 获取详细信息
func (*SlogError) WithDetails ¶ added in v0.1.0
WithDetails 添加详细信息
type SubscribeOptions ¶ added in v0.2.0
type SubscribeOptions struct {
// BufferSize 订阅缓冲区大小。
BufferSize uint16
// Backpressure 背压策略;空值时默认 drop_oldest。
Backpressure SubscriptionBackpressurePolicy
// BlockTimeout 仅在 block_with_timeout 模式下生效。
BlockTimeout time.Duration
}
SubscribeOptions 订阅选项。
type SubscriberStats ¶ added in v0.2.0
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 ¶ added in v0.2.0
func GetSubscriberStats(id int64) (SubscriberStats, bool)
GetSubscriberStats 根据订阅ID返回统计快照。
func ListSubscriberStats ¶ added in v0.2.0
func ListSubscriberStats() []SubscriberStats
ListSubscriberStats 返回所有订阅者统计快照(按订阅ID升序)。
type SubscriptionBackpressurePolicy ¶ added in v0.2.0
type SubscriptionBackpressurePolicy string
SubscriptionBackpressurePolicy 定义订阅通道在高压场景下的背压策略。
const ( // SubscriptionDropOldest 丢弃最旧消息,优先保留最新数据(默认)。 SubscriptionDropOldest SubscriptionBackpressurePolicy = "drop_oldest" // SubscriptionDropNewest 丢弃最新消息,优先保留已入队数据。 SubscriptionDropNewest SubscriptionBackpressurePolicy = "drop_newest" // SubscriptionBlockWithTimeout 在超时时间内阻塞等待可写,超时后丢弃。 SubscriptionBlockWithTimeout SubscriptionBackpressurePolicy = "block_with_timeout" )
type SubscriptionEvent ¶ added in v0.2.0
type SubscriptionEvent struct {
// Record 是已应用前缀、formatter、DLP 与 context 字段后的结构化日志。
Record slog.Record
// Rendered 是与当前激活主输出一致的最终语义化内容;若未启用任何输出则为空。
Rendered string
// Format 表示 Rendered 采用的格式,取值为 text、json 或空字符串。
Format string
}
SubscriptionEvent 描述一次统一发布后的订阅事件。 其中 Record 保留结构化视图,Rendered 则严格跟随当前激活的主输出格式。
type SubscriptionStats ¶ added in v0.2.0
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 ¶ added in v0.2.0
func GetSubscriptionStats() SubscriptionStats
GetSubscriptionStats 返回订阅系统汇总统计。