Documentation
¶
Overview ¶
* @Author: kamalyes 501893067@qq.com * @Date: 2025-12-19 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-12-19 22:59:30 * @FilePath: \go-toolbox\pkg\logger\console.go * @Description: JavaScript console 风格的日志分组和表格功能 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-10-01 10:38:52 * @FilePath: \go-toolbox\pkg\logger\context.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-09-18 11:15:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-12-19 23:27:35 * @FilePath: \go-toolbox\pkg\logger\empty.go * @Description: 空日志实现,用于禁用日志输出的场景 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-01-26 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-09-30 18:02:53 * @FilePath: \go-toolbox\pkg\logger\escape.go * @Description: 文本模式控制字符转义(防日志注入,保持一条日志恒为一行) * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-01-26 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-10-01 18:30:05 * @FilePath: \go-toolbox\pkg\logger\failure.go * @Description: 持续失败的限频汇总(避免故障期间日志风暴) * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-08-26 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-10-02 11:06:28 * @FilePath: \go-toolbox\pkg\logger\fields.go * @Description: 字段 Logger 的预编码字段存储与写出路径 * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-01-26 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-10-01 18:30:05 * @FilePath: \go-toolbox\pkg\logger\identity.go * @Description: 服务身份固定字段(service / instance / env) * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-09 16:00:00 * @FilePath: \go-toolbox\pkg\logger\interfaces.go * @Description: 日志接口定义 - 增强版本,支持多种日志框架的参数格式 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-22 12:33:32 * @FilePath: \go-toolbox\pkg\logger\level.go * @Description: 统一的日志级别定义和管理 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-01-26 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-10-02 11:06:28 * @FilePath: \go-toolbox\pkg\logger\limit.go * @Description: 单条日志的字节上限与超限裁剪 * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-10-02 11:06:28 * @FilePath: \go-toolbox\pkg\logger\logger.go * @Description: 统一的日志工具包,支持 emoji 和结构化日志 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-02-02 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-02-02 00:00:00 * @FilePath: \go-toolbox\pkg\logger\output.go * @Description: 输出类型和配置 * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-01-26 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-10-02 09:57:31 * @FilePath: \go-toolbox\pkg\logger\sanitize.go * @Description: 敏感字段脱敏(按字段名零分配判定 + 可选的值内容扫描) * * 规则表与字段名判定已迁至 github.com/HitGameAI/apex-toolbox/pkg/desensitize: * 那 200 余条敏感字段名、后缀规则与运维豁免表属于安全基线,同时存在两份迟早漂移, * 而报文脱敏、结构体脱敏等场景同样需要它们 * 迁走的是不依赖 Logger 的纯逻辑(规则表、形状位图、后缀字典树、掩码追加器), * 本文件保留 Logger 侧的接入:脱敏强度开关、与 JSON / text 编码器的衔接、 * 值内容扫描与长度截断的配合 * * 日志用的是严格档 ActionForKey(精确 + 后缀 + 运维豁免): * 误擦会让 service_name、status_code 这类排障主线索消失,宁可漏擦由调用方补注册 * 报文脱敏用的是宽松档,见 go-desensitize 的 doc.go * * 不保留同名转发层:本库尚无外部使用者依赖这些内部符号,直呼上游更易读 * go-desensitize 自身零第三方依赖,因此本库的依赖闭包只增加它一个包 * * [EN] The rule tables and key-name decision moved to go-desensitize: those * 200-odd key names, suffix rules and ops-visibility exemptions are a security * baseline that would drift if kept in two places. Only the Logger-side glue * stays here. Logs use the strict strength, where a false positive erases the * operator's diagnostic trail. go-desensitize has no third-party dependencies * of its own, so this library's closure grows by exactly one package * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-01-26 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-10-02 09:57:31 * @FilePath: \go-toolbox\pkg\logger\scan.go * @Description: 文本内容的敏感信息扫描(SanitizeKeysAndValues 模式,手写单遍扫描) * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-01-27 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-10-01 09:26:08 * @FilePath: \go-toolbox\pkg\logger\stdout.go * @Description: 进程级共享的标准流异步输出器(默认输出目标) * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-03-01 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-03-01 03:36:57 * @FilePath: \go-toolbox\pkg\logger\time.go * @Description: 时间戳追加快速路径(秒级前缀缓存 + 跳过 layout 逐 chunk 解析) * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-12-19 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-12-19 23:52:45 * @FilePath: \go-toolbox\pkg\logger\timer.go * @Description: 计时器功能,类似 JavaScript console.time() * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-01-27 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-10-01 09:26:08 * @FilePath: \go-toolbox\pkg\logger\tty.go * @Description: 输出目标的着色能力探测(NO_COLOR / 字符设备判定) * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-10-01 18:30:05 * @FilePath: \go-toolbox\pkg\logger\types.go * @Description: 核心类型定义 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-09-10 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-09-30 18:02:53 * @FilePath: \go-toolbox\pkg\logger\value.go * @Description: 值格式化与显示宽度工具(自包含实现,零外部依赖) * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-10-02 15:19:07 * @FilePath: \go-toolbox\pkg\logger\writer.go * @Description: 日志输出器实现 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
Index ¶
- Constants
- Variables
- func CleanupExpiredTimers(maxAge time.Duration) int
- func Close() error
- func ContextWithTraceID(ctx context.Context, traceID string) context.Context
- func DefaultContextKeys() []compiledContextKey
- func DetectInstance() string
- func ExtractTraceFromIncoming(ctx context.Context) string
- func ExtractTraceID(ctx context.Context) string
- func Flush() error
- func GetActiveTimersCount() int
- func GetAllCategories() []string
- func GetAllLevelNames() []string
- func GetLevelNames() []string
- func GetLevelShortNames() []string
- func InjectTraceToOutgoing(ctx context.Context, traceID string) context.Context
- func IsEmptyLogger(logger ILogger) bool
- func RegisterSensitiveKeys(keys ...string)
- func RestoreTraceFromIncoming(ctx context.Context) context.Context
- func SetGlobalLevel(level LogLevel)
- func SetGlobalShowCaller(show bool)
- func SetTimerCleanupInterval(interval time.Duration)
- func SetTimerMaxAge(maxAge time.Duration)
- func UnregisterSensitiveKeys(keys ...string)
- type BufferedWriter
- func (w *BufferedWriter) Close() error
- func (w *BufferedWriter) Flush() error
- func (w *BufferedWriter) GetStats() WriterStatsSnapshot
- func (w *BufferedWriter) IsHealthy() bool
- func (w *BufferedWriter) Write(p []byte) (n int, err error)
- func (w *BufferedWriter) WriteLevel(level LogLevel, data []byte) (n int, err error)
- type BufferedWriterOption
- type CallerInfo
- type ConsoleGroup
- func (cg *ConsoleGroup) Debug(format string, args ...interface{})
- func (cg *ConsoleGroup) DebugContext(ctx context.Context, format string, args ...interface{})
- func (cg *ConsoleGroup) Error(format string, args ...interface{})
- func (cg *ConsoleGroup) ErrorContext(ctx context.Context, format string, args ...interface{})
- func (cg *ConsoleGroup) Group(label string, args ...interface{})
- func (cg *ConsoleGroup) GroupCollapsed(label string, args ...interface{})
- func (cg *ConsoleGroup) GroupEnd()
- func (cg *ConsoleGroup) Info(format string, args ...interface{})
- func (cg *ConsoleGroup) InfoContext(ctx context.Context, format string, args ...interface{})
- func (cg *ConsoleGroup) Log(level LogLevel, format string, args ...interface{})
- func (cg *ConsoleGroup) Table(data interface{})
- func (cg *ConsoleGroup) Time(label string) *Timer
- func (cg *ConsoleGroup) Warn(format string, args ...interface{})
- func (cg *ConsoleGroup) WarnContext(ctx context.Context, format string, args ...interface{})
- type ConsoleTable
- type ConsoleWriterOption
- func WithConsoleBatchBytes(bytes int) ConsoleWriterOption
- func WithConsoleColor(color bool) ConsoleWriterOption
- func WithConsoleFlushInterval(interval time.Duration) ConsoleWriterOption
- func WithConsoleLevel(level LogLevel) ConsoleWriterOption
- func WithConsoleOutput(output io.Writer) ConsoleWriterOption
- func WithConsoleQueueSize(bytes int) ConsoleWriterOption
- type ContextExtractor
- type EmptyAdapter
- func (e *EmptyAdapter) Close() error
- func (e *EmptyAdapter) Flush() error
- func (e *EmptyAdapter) GetAdapterName() string
- func (e *EmptyAdapter) GetAdapterVersion() string
- func (e *EmptyAdapter) Initialize() error
- func (e *EmptyAdapter) IsHealthy() bool
- func (e *EmptyAdapter) SetHealthy(healthy bool)
- type EmptyHook
- type EmptyLogger
- func (e *EmptyLogger) Clone() ILogger
- func (e *EmptyLogger) ConsoleGroup(label string, args ...interface{})
- func (e *EmptyLogger) ConsoleGroupCollapsed(label string, args ...interface{})
- func (e *EmptyLogger) ConsoleGroupEnd()
- func (e *EmptyLogger) ConsoleTable(data interface{})
- func (e *EmptyLogger) ConsoleTime(label string) *Timer
- func (e *EmptyLogger) Debug(format string, args ...interface{})
- func (e *EmptyLogger) DebugContext(ctx context.Context, format string, args ...interface{})
- func (e *EmptyLogger) DebugContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
- func (e *EmptyLogger) DebugContextLines(ctx context.Context, lines ...string)
- func (e *EmptyLogger) DebugCtxReturn(ctx context.Context, format string, args ...interface{}) error
- func (e *EmptyLogger) DebugKV(msg string, keysAndValues ...interface{})
- func (e *EmptyLogger) DebugKVReturn(msg string, keysAndValues ...interface{}) error
- func (e *EmptyLogger) DebugLines(lines ...string)
- func (e *EmptyLogger) DebugMsg(msg string)
- func (e *EmptyLogger) DebugReturn(format string, args ...interface{}) error
- func (e *EmptyLogger) DebugWithFields(msg string, fields map[string]interface{})
- func (e *EmptyLogger) Debugf(format string, args ...interface{})
- func (e *EmptyLogger) Error(format string, args ...interface{})
- func (e *EmptyLogger) ErrorContext(ctx context.Context, format string, args ...interface{})
- func (e *EmptyLogger) ErrorContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
- func (e *EmptyLogger) ErrorContextLines(ctx context.Context, lines ...string)
- func (e *EmptyLogger) ErrorCtxReturn(ctx context.Context, format string, args ...interface{}) error
- func (e *EmptyLogger) ErrorKV(msg string, keysAndValues ...interface{})
- func (e *EmptyLogger) ErrorKVReturn(msg string, keysAndValues ...interface{}) error
- func (e *EmptyLogger) ErrorLines(lines ...string)
- func (e *EmptyLogger) ErrorMsg(msg string)
- func (e *EmptyLogger) ErrorReturn(format string, args ...interface{}) error
- func (e *EmptyLogger) ErrorWithFields(msg string, fields map[string]interface{})
- func (e *EmptyLogger) Errorf(format string, args ...interface{})
- func (e *EmptyLogger) Fatal(format string, args ...interface{})
- func (e *EmptyLogger) FatalContext(ctx context.Context, format string, args ...interface{})
- func (e *EmptyLogger) FatalContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
- func (e *EmptyLogger) FatalKV(msg string, keysAndValues ...interface{})
- func (e *EmptyLogger) FatalMsg(msg string)
- func (e *EmptyLogger) FatalWithFields(msg string, fields map[string]interface{})
- func (e *EmptyLogger) Fatalf(format string, args ...interface{})
- func (e *EmptyLogger) GetLevel() LogLevel
- func (e *EmptyLogger) GetStats() *LoggerStats
- func (e *EmptyLogger) Info(format string, args ...interface{})
- func (e *EmptyLogger) InfoContext(ctx context.Context, format string, args ...interface{})
- func (e *EmptyLogger) InfoContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
- func (e *EmptyLogger) InfoContextLines(ctx context.Context, lines ...string)
- func (e *EmptyLogger) InfoCtxReturn(ctx context.Context, format string, args ...interface{}) error
- func (e *EmptyLogger) InfoKV(msg string, keysAndValues ...interface{})
- func (e *EmptyLogger) InfoKVReturn(msg string, keysAndValues ...interface{}) error
- func (e *EmptyLogger) InfoLines(lines ...string)
- func (e *EmptyLogger) InfoMsg(msg string)
- func (e *EmptyLogger) InfoReturn(format string, args ...interface{}) error
- func (e *EmptyLogger) InfoWithFields(msg string, fields map[string]interface{})
- func (e *EmptyLogger) Infof(format string, args ...interface{})
- func (e *EmptyLogger) IsLevelEnabled(level LogLevel) bool
- func (e *EmptyLogger) IsShowCaller() bool
- func (e *EmptyLogger) Log(level LogLevel, msg string)
- func (e *EmptyLogger) LogContext(ctx context.Context, level LogLevel, msg string)
- func (e *EmptyLogger) LogKV(level LogLevel, msg string, keysAndValues ...interface{})
- func (e *EmptyLogger) LogSpecialContext(ctx context.Context, logType SpecialLogType, level LogLevel, format string, ...)
- func (e *EmptyLogger) LogWithFields(level LogLevel, msg string, fields map[string]interface{})
- func (e *EmptyLogger) NewConsoleGroup() *ConsoleGroup
- func (e *EmptyLogger) Print(args ...interface{})
- func (e *EmptyLogger) Printf(format string, args ...interface{})
- func (e *EmptyLogger) Println(args ...interface{})
- func (e *EmptyLogger) SetLevel(level LogLevel)
- func (e *EmptyLogger) SetShowCaller(show bool)
- func (e *EmptyLogger) Warn(format string, args ...interface{})
- func (e *EmptyLogger) WarnContext(ctx context.Context, format string, args ...interface{})
- func (e *EmptyLogger) WarnContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
- func (e *EmptyLogger) WarnContextLines(ctx context.Context, lines ...string)
- func (e *EmptyLogger) WarnCtxReturn(ctx context.Context, format string, args ...interface{}) error
- func (e *EmptyLogger) WarnKV(msg string, keysAndValues ...interface{})
- func (e *EmptyLogger) WarnKVReturn(msg string, keysAndValues ...interface{}) error
- func (e *EmptyLogger) WarnLines(lines ...string)
- func (e *EmptyLogger) WarnMsg(msg string)
- func (e *EmptyLogger) WarnReturn(format string, args ...interface{}) error
- func (e *EmptyLogger) WarnWithFields(msg string, fields map[string]interface{})
- func (e *EmptyLogger) Warnf(format string, args ...interface{})
- func (e *EmptyLogger) WithContext(ctx context.Context) ILogger
- func (e *EmptyLogger) WithError(err error) ILogger
- func (e *EmptyLogger) WithField(key string, value interface{}) ILogger
- func (e *EmptyLogger) WithFields(fields map[string]interface{}) ILogger
- type EmptyWriter
- type FailureLog
- type FailureLogConfig
- type FailureState
- type FileLogWriter
- func (w *FileLogWriter) Close() error
- func (w *FileLogWriter) Flush() error
- func (w *FileLogWriter) GetStats() WriterStatsSnapshot
- func (w *FileLogWriter) IsHealthy() bool
- func (w *FileLogWriter) Write(p []byte) (n int, err error)
- func (w *FileLogWriter) WriteLevel(level LogLevel, data []byte) (n int, err error)
- type FileWriterOption
- type FormatType
- type IAdapter
- type IAdvancedLogger
- type IFileWriter
- type IFormatter
- type IFrameworkAdapter
- type IHook
- type ILogBuilder
- type ILogger
- type ILogrusLogger
- type IManager
- type IMiddleware
- type ISlogLogger
- type IWriter
- func CreateWriter(config *WriterConfig) (IWriter, error)
- func DefaultOutput() IWriter
- func NewBufferedWriter(opts ...BufferedWriterOption) IWriter
- func NewConsoleWriter(opts ...ConsoleWriterOption) IWriter
- func NewFileWriter(opts ...FileWriterOption) IWriter
- func NewMultiWriter(opts ...MultiWriterOption) IWriter
- func NewRotateWriter(opts ...RotateWriterOption) IWriter
- func StderrOutput() IWriter
- type IZapLogger
- type IZerologLogger
- type LevelInfo
- type LogArgs
- type LogEntry
- type LogLevel
- func (l LogLevel) Category() string
- func (l LogLevel) Color() string
- func (l LogLevel) Description() string
- func (l LogLevel) Emoji() string
- func (l LogLevel) Info() LevelInfo
- func (l LogLevel) IsApplication() bool
- func (l LogLevel) IsBasic() bool
- func (l LogLevel) IsBusiness() bool
- func (l LogLevel) IsEnabled(target LogLevel) bool
- func (l LogLevel) IsPerformance() bool
- func (l LogLevel) IsSecurity() bool
- func (l LogLevel) IsSystem() bool
- func (l LogLevel) IsValid() bool
- func (l LogLevel) MarshalText() ([]byte, error)
- func (l LogLevel) Priority() int
- func (l LogLevel) ShortString() string
- func (l LogLevel) String() string
- func (l *LogLevel) UnmarshalText(text []byte) error
- func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error
- type Logger
- func (l *Logger) Audit(action, user, resource, result string)
- func (l *Logger) Cache(format string, args ...any)
- func (l *Logger) Clone() ILogger
- func (l *Logger) ConfigLog(format string, args ...any)
- func (l *Logger) ConsoleGroup(label string, args ...any)
- func (l *Logger) ConsoleGroupCollapsed(label string, args ...any)
- func (l *Logger) ConsoleGroupEnd()
- func (l *Logger) ConsoleTable(data any)
- func (l *Logger) ConsoleTime(label string) *Timer
- func (l *Logger) Database(format string, args ...any)
- func (l *Logger) Debug(format string, args ...any)
- func (l *Logger) DebugContext(ctx context.Context, format string, args ...any)
- func (l *Logger) DebugContextKV(ctx context.Context, msg string, keysAndValues ...any)
- func (l *Logger) DebugContextLines(ctx context.Context, lines ...string)
- func (l *Logger) DebugCtxReturn(ctx context.Context, format string, args ...any) error
- func (l *Logger) DebugKV(msg string, keysAndValues ...any)
- func (l *Logger) DebugKVReturn(msg string, keysAndValues ...any) error
- func (l *Logger) DebugLines(lines ...string)
- func (l *Logger) DebugMsg(msg string)
- func (l *Logger) DebugReturn(format string, args ...any) error
- func (l *Logger) DebugWithFields(msg string, fields map[string]any)
- func (l *Logger) Debugf(format string, args ...any)
- func (l *Logger) Env() string
- func (l *Logger) Environment(format string, args ...any)
- func (l *Logger) Error(format string, args ...any)
- func (l *Logger) ErrorContext(ctx context.Context, format string, args ...any)
- func (l *Logger) ErrorContextKV(ctx context.Context, msg string, keysAndValues ...any)
- func (l *Logger) ErrorContextLines(ctx context.Context, lines ...string)
- func (l *Logger) ErrorCtxReturn(ctx context.Context, format string, args ...any) error
- func (l *Logger) ErrorKV(msg string, keysAndValues ...any)
- func (l *Logger) ErrorKVReturn(msg string, keysAndValues ...any) error
- func (l *Logger) ErrorLines(lines ...string)
- func (l *Logger) ErrorMsg(msg string)
- func (l *Logger) ErrorReturn(format string, args ...any) error
- func (l *Logger) ErrorWithFields(msg string, fields map[string]any)
- func (l *Logger) Errorf(format string, args ...any)
- func (l *Logger) Fatal(format string, args ...any)
- func (l *Logger) FatalContext(ctx context.Context, format string, args ...any)
- func (l *Logger) FatalContextKV(ctx context.Context, msg string, keysAndValues ...any)
- func (l *Logger) FatalKV(msg string, keysAndValues ...any)
- func (l *Logger) FatalMsg(msg string)
- func (l *Logger) FatalWithFields(msg string, fields map[string]any)
- func (l *Logger) Fatalf(format string, args ...any)
- func (l *Logger) Flush() error
- func (l *Logger) GetContextExtractor() ContextExtractor
- func (l *Logger) GetLevel() LogLevel
- func (l *Logger) Health(service string, status bool, details string)
- func (l *Logger) Info(format string, args ...any)
- func (l *Logger) InfoContext(ctx context.Context, format string, args ...any)
- func (l *Logger) InfoContextKV(ctx context.Context, msg string, keysAndValues ...any)
- func (l *Logger) InfoContextLines(ctx context.Context, lines ...string)
- func (l *Logger) InfoCtxReturn(ctx context.Context, format string, args ...any) error
- func (l *Logger) InfoKV(msg string, keysAndValues ...any)
- func (l *Logger) InfoKVReturn(msg string, keysAndValues ...any) error
- func (l *Logger) InfoLines(lines ...string)
- func (l *Logger) InfoMsg(msg string)
- func (l *Logger) InfoReturn(format string, args ...any) error
- func (l *Logger) InfoWithFields(msg string, fields map[string]any)
- func (l *Logger) Infof(format string, args ...any)
- func (l *Logger) Instance() string
- func (l *Logger) IsLevelEnabled(level LogLevel) bool
- func (l *Logger) IsShowCaller() bool
- func (l *Logger) Loading(format string, args ...any)
- func (l *Logger) Log(level LogLevel, msg string)
- func (l *Logger) LogContext(ctx context.Context, level LogLevel, msg string)
- func (l *Logger) LogKV(level LogLevel, msg string, keysAndValues ...any)
- func (l *Logger) LogSpecialContext(ctx context.Context, logType SpecialLogType, level LogLevel, format string, ...)
- func (l *Logger) LogWithFields(level LogLevel, msg string, fields map[string]any)
- func (l *Logger) Milestone(message string)
- func (l *Logger) Network(format string, args ...any)
- func (l *Logger) NewConsoleGroup() *ConsoleGroup
- func (l *Logger) Performance(operation string, duration time.Duration, details ...map[string]any)
- func (l *Logger) Print(args ...any)
- func (l *Logger) Printf(format string, args ...any)
- func (l *Logger) Println(args ...any)
- func (l *Logger) Progress(current, total int, operation string)
- func (l *Logger) Security(format string, args ...any)
- func (l *Logger) Service() string
- func (l *Logger) SetContextExtractor(extractor ContextExtractor)
- func (l *Logger) SetLevel(level LogLevel)
- func (l *Logger) SetShowCaller(show bool)
- func (l *Logger) Start(format string, args ...any)
- func (l *Logger) StartTiming(operation string) *Timing
- func (l *Logger) Stop(format string, args ...any)
- func (l *Logger) Success(format string, args ...any)
- func (l *Logger) Warn(format string, args ...any)
- func (l *Logger) WarnContext(ctx context.Context, format string, args ...any)
- func (l *Logger) WarnContextKV(ctx context.Context, msg string, keysAndValues ...any)
- func (l *Logger) WarnContextLines(ctx context.Context, lines ...string)
- func (l *Logger) WarnCtxReturn(ctx context.Context, format string, args ...any) error
- func (l *Logger) WarnKV(msg string, keysAndValues ...any)
- func (l *Logger) WarnKVReturn(msg string, keysAndValues ...any) error
- func (l *Logger) WarnLines(lines ...string)
- func (l *Logger) WarnMsg(msg string)
- func (l *Logger) WarnReturn(format string, args ...any) error
- func (l *Logger) WarnWithFields(msg string, fields map[string]any)
- func (l *Logger) Warnf(format string, args ...any)
- func (l *Logger) WithCallerDepth(depth int) *Logger
- func (l *Logger) WithCallerKey(key string) *Logger
- func (l *Logger) WithColorful(colorful bool) *Logger
- func (l *Logger) WithContext(ctx context.Context) ILogger
- func (l *Logger) WithContextExtractor(extractor ContextExtractor) *Logger
- func (l *Logger) WithContextKeys(keys ...string) *Logger
- func (l *Logger) WithEnv(env string) *Logger
- func (l *Logger) WithError(err error) ILogger
- func (l *Logger) WithField(key string, value any) ILogger
- func (l *Logger) WithFields(fields map[string]any) ILogger
- func (l *Logger) WithFormat(format FormatType) *Logger
- func (l *Logger) WithFormatter(formatter IFormatter) *Logger
- func (l *Logger) WithHooks(hooks []IHook) *Logger
- func (l *Logger) WithInstance(instance string) *Logger
- func (l *Logger) WithLevel(level LogLevel) *Logger
- func (l *Logger) WithLevelKey(key string) *Logger
- func (l *Logger) WithMaxFieldBytes(max int) *Logger
- func (l *Logger) WithMaxLineBytes(max int) *Logger
- func (l *Logger) WithMessageKey(key string) *Logger
- func (l *Logger) WithMiddleware(middleware []IMiddleware) *Logger
- func (l *Logger) WithOutput(output io.Writer) *Logger
- func (l *Logger) WithPrefix(prefix string) *Logger
- func (l *Logger) WithSanitize(mode SanitizeMode) *Logger
- func (l *Logger) WithService(service string) *Logger
- func (l *Logger) WithShowCaller(show bool) *Logger
- func (l *Logger) WithShowStacktrace(show bool) *Logger
- func (l *Logger) WithStacktraceKey(key string) *Logger
- func (l *Logger) WithTimeFormat(format string) *Logger
- func (l *Logger) WithTimestampKey(key string) *Logger
- func (l *Logger) WithWriters(writers []IWriter) *Logger
- type LoggerStats
- type MultiLogWriter
- func (w *MultiLogWriter) Close() error
- func (w *MultiLogWriter) Flush() error
- func (w *MultiLogWriter) GetStats() WriterStatsSnapshot
- func (w *MultiLogWriter) IsHealthy() bool
- func (w *MultiLogWriter) Write(p []byte) (n int, err error)
- func (w *MultiLogWriter) WriteLevel(level LogLevel, data []byte) (n int, err error)
- type MultiWriterOption
- type OutputType
- type PerformanceLevel
- type RotateLogWriter
- func (w *RotateLogWriter) Close() error
- func (w *RotateLogWriter) Flush() error
- func (w *RotateLogWriter) GetStats() WriterStatsSnapshot
- func (w *RotateLogWriter) IsHealthy() bool
- func (w *RotateLogWriter) Write(p []byte) (n int, err error)
- func (w *RotateLogWriter) WriteLevel(level LogLevel, data []byte) (n int, err error)
- type RotateWriterOption
- func WithCompress(compress bool) RotateWriterOption
- func WithFilePath(filePath string) RotateWriterOption
- func WithMaxAge(maxAge time.Duration) RotateWriterOption
- func WithMaxFiles(maxFiles int) RotateWriterOption
- func WithMaxSize(maxSize int64) RotateWriterOption
- func WithRotateBufferSize(size int) RotateWriterOption
- func WithRotateLevel(level LogLevel) RotateWriterOption
- func WithRotatePermission(permission os.FileMode) RotateWriterOption
- type SanitizeMode
- type SpecialLogType
- type Timer
- type Timing
- type WriterConfig
- type WriterStatsSnapshot
Constants ¶
const ( // DefaultFailureInterval 汇总间隔的默认值 DefaultFailureInterval = time.Minute // FieldFailureCount 本轮连续失败的累计次数 FieldFailureCount = "failure_count" // FieldSuppressedCount 自上一条汇总以来被压制的失败次数 FieldSuppressedCount = "suppressed_count" // FieldFailureDurationMS 自首次失败起的持续时长(毫秒) FieldFailureDurationMS = "failure_duration_ms" )
const ( // FieldService 服务名字段 FieldService = "service" // FieldInstance 实例(副本)标识字段 FieldInstance = "instance" // FieldEnv 部署环境字段 FieldEnv = "env" )
const ( ColorBlack = "\033[30m" ColorRed = "\033[31m" ColorGreen = "\033[32m" ColorYellow = "\033[33m" ColorBlue = "\033[34m" ColorMagenta = "\033[35m" ColorCyan = "\033[36m" ColorWhite = "\033[37m" ColorGray = "\033[90m" // 亮色版本 ColorBrightRed = "\033[91m" ColorBrightGreen = "\033[92m" ColorBrightYellow = "\033[93m" ColorBrightBlue = "\033[94m" ColorBrightMagenta = "\033[95m" ColorBrightCyan = "\033[96m" ColorBrightWhite = "\033[97m" )
预定义颜色常量
const ( DefaultMaxSize = 100 * 1024 * 1024 // 默认最大文件大小 100MB DefaultMaxFiles = 5 // 默认最大文件数 DefaultFilePermission = 0644 // 默认文件权限 DefaultDirPermission = 0755 // 默认目录权限 DefaultMaxAge = 30 * 24 * time.Hour // 默认最大保留时间 30天 DefaultBufferSize = 4096 // 默认缓冲区大小 4KB DefaultConsoleQueueSize = 4096 // 控制台输出器异步队列深度(条数) DefaultConsoleBatchBytes = 64 * 1024 // 控制台输出器合并写出字节上限(单次写出体量) DefaultConsoleFlushInterval = 100 * time.Millisecond // 控制台输出器定时刷写间隔 )
默认配置常量
const ( ErrMsgFilePathEmpty = "file_path is required for file output" ErrMsgRotatePathEmpty = "file_path is required for rotate output" )
错误消息常量
const ColorReset = "\033[0m"
ColorReset 颜色重置代码
const ContextKeyTraceID = "trace_id"
ContextKeyTraceID 是 traceId 在日志输出的字段名,同时作为 ctx.Value 的 fallback key traceId 的唯一真相源是 OTel span(gRPC 的 otelgrpc StatsHandler / HTTP 的 Tracing 中间件创建) extract 优先从 OTel span 提取;当 ctx 不在 span 内时,fallback 到 ctx.Value("trace_id")
const ( // DefaultMaxLineBytes 单条日志的默认字节上限 // // 取 64KB:正常日志(含带堆栈的错误日志)远低于此值,不会被动截断; // 同时把失控的大 payload 挡在对象池阈值的量级附近,避免池抖动扩散 DefaultMaxLineBytes = 64 * 1024 )
Variables ¶
var ( SuccessType = SpecialLogType{"✅", "SUCCESS"} LoadingType = SpecialLogType{"⏳", "LOADING"} ConfigType = SpecialLogType{"⚙️", "CONFIG"} StartType = SpecialLogType{"🚀", "START"} StopType = SpecialLogType{"🛑", "STOP"} DatabaseType = SpecialLogType{"💾", "DATABASE"} NetworkType = SpecialLogType{"🌐", "NETWORK"} SecurityType = SpecialLogType{"🔒", "SECURITY"} CacheType = SpecialLogType{"🗄️", "CACHE"} EnvironmentType = SpecialLogType{"🌍", "ENV"} )
特殊日志类型定义
Functions ¶
func CleanupExpiredTimers ¶
CleanupExpiredTimers 手动清理超过指定时间未结束的计时器
func Close ¶
func Close() error
Close 刷写并关闭共享标准流输出器(停止后台 flusher) 不关闭 os.Stdout/os.Stderr 本身,关闭后向该输出器写日志将失败, 故仅应在进程退出前调用;常规优雅退出用 Flush 即可
func ContextWithTraceID ¶
ContextWithTraceID 创建携带 trace_id 的 context 如果 ctx 已有 trace_id 则不覆盖(尊重上游传入的值)
func DefaultContextKeys ¶
func DefaultContextKeys() []compiledContextKey
DefaultContextKeys 返回默认上下文提取 key
func DetectInstance ¶
func DetectInstance() string
DetectInstance 推导当前实例标识 依次尝试 INSTANCE_ID、POD_NAME、HOSTNAME 环境变量,再回落到主机名,最后返回 unknown
func ExtractTraceFromIncoming ¶
ExtractTraceFromIncoming 从 gRPC incoming metadata 提取 trace_id 优先级:OTel span > metadata > ctx.Value 用于 gRPC 服务端接收到远程节点请求时恢复 trace
func ExtractTraceID ¶
ExtractTraceID 从 ctx 提取 trace_id 优先级:OTel span > ctx.Value(ContextKeyTraceID) > 空 直接复用 context.go 的 extractOTelTraceID,保证与日志输出使用同一真相源
func Flush ¶
func Flush() error
Flush 刷写共享标准流输出器中已入队但未落盘的日志条目
应在优雅退出链路(SIGTERM/SIGINT 处理、main 的 defer)中调用, 否则队列中最多 DefaultConsoleFlushInterval 内的条目会随进程退出丢失:
func main() {
defer logger.Flush()
...
}
只刷写已被构造的单例,未使用过的流不会因此被初始化
func InjectTraceToOutgoing ¶
InjectTraceToOutgoing 将 trace_id 注入 gRPC outgoing metadata 用于 gRPC 客户端调用远程节点时传播 trace 确保 OTel 未启用时仍可传播
func RegisterSensitiveKeys ¶
func RegisterSensitiveKeys(keys ...string)
RegisterSensitiveKeys 追加自定义敏感字段名(归一化后参与精确匹配,整体擦除) 全进程生效:敏感字段清单属于安全基线,不应因 Logger 实例不同而不同 应在启动阶段调用完毕,规则表在日志路径上只读
func RestoreTraceFromIncoming ¶
RestoreTraceFromIncoming 从 gRPC incoming 恢复 trace_id 到 ctx 如果提取到 trace_id 但 ctx 中没有,则注入到 ctx.Value 返回增强后的 ctx,供下游 logger 自动输出 trace_id
func SetTimerCleanupInterval ¶
SetTimerCleanupInterval 设置清理间隔(可选配置,立即生效,触发 cleanup goroutine 重建 ticker)
func SetTimerMaxAge ¶
SetTimerMaxAge 设置计时器最大存活时间(可选配置,热更新,线程安全)
func UnregisterSensitiveKeys ¶
func UnregisterSensitiveKeys(keys ...string)
UnregisterSensitiveKeys 移除此前追加的敏感字段名,内置规则不受影响 主要供测试在用例之间复原全局状态
Types ¶
type BufferedWriter ¶
type BufferedWriter struct {
// contains filtered or unexported fields
}
BufferedWriter 缓冲输出器(为底层输出器添加可配置的缓冲层)
func (*BufferedWriter) GetStats ¶
func (w *BufferedWriter) GetStats() WriterStatsSnapshot
GetStats 获取统计信息
func (*BufferedWriter) Write ¶
func (w *BufferedWriter) Write(p []byte) (n int, err error)
Write 实现io.Writer接口
func (*BufferedWriter) WriteLevel ¶
func (w *BufferedWriter) WriteLevel(level LogLevel, data []byte) (n int, err error)
WriteLevel 按级别写入
type BufferedWriterOption ¶
type BufferedWriterOption func(*BufferedWriter)
BufferedWriterOption 缓冲输出器配置选项
func WithBufferSize ¶
func WithBufferSize(bufferSize int) BufferedWriterOption
WithBufferSize 设置缓冲区大小
func WithBufferedLevel ¶
func WithBufferedLevel(level LogLevel) BufferedWriterOption
WithBufferedLevel 设置日志级别
func WithBufferedUnderlying ¶
func WithBufferedUnderlying(underlying IWriter) BufferedWriterOption
WithBufferedUnderlying 设置底层输出器
type CallerInfo ¶
type CallerInfo struct {
File string `json:"file"`
Line int `json:"line"`
Function string `json:"function"`
}
CallerInfo 调用者信息
type ConsoleGroup ¶
type ConsoleGroup struct {
// contains filtered or unexported fields
}
ConsoleGroup 控制台分组 所有输出直接写入 output(默认 os.Stdout),不走 logger 的 JSON/文本格式化 这样启动横幅、表格等控制台展示内容不会污染 JSON 日志流
func NewConsoleGroup ¶
func NewConsoleGroup() *ConsoleGroup
NewConsoleGroup 创建新的控制台分组(包级函数,输出到 os.Stdout)
func (*ConsoleGroup) Debug ¶
func (cg *ConsoleGroup) Debug(format string, args ...interface{})
Debug 在分组中记录 Debug 级别日志
func (*ConsoleGroup) DebugContext ¶
func (cg *ConsoleGroup) DebugContext(ctx context.Context, format string, args ...interface{})
DebugContext 在分组中记录带上下文的 Debug 级别日志
func (*ConsoleGroup) Error ¶
func (cg *ConsoleGroup) Error(format string, args ...interface{})
Error 在分组中记录 Error 级别日志
func (*ConsoleGroup) ErrorContext ¶
func (cg *ConsoleGroup) ErrorContext(ctx context.Context, format string, args ...interface{})
ErrorContext 在分组中记录带上下文的 Error 级别日志
func (*ConsoleGroup) Group ¶
func (cg *ConsoleGroup) Group(label string, args ...interface{})
Group 开始一个新的日志分组 类似 JavaScript console.group()
func (*ConsoleGroup) GroupCollapsed ¶
func (cg *ConsoleGroup) GroupCollapsed(label string, args ...interface{})
GroupCollapsed 开始一个折叠的日志分组 类似 JavaScript console.groupCollapsed() 在折叠状态下,该分组内的日志将不会输出(除非日志级别为 ERROR 或 FATAL)
func (*ConsoleGroup) GroupEnd ¶
func (cg *ConsoleGroup) GroupEnd()
GroupEnd 结束当前分组 类似 JavaScript console.groupEnd()
func (*ConsoleGroup) Info ¶
func (cg *ConsoleGroup) Info(format string, args ...interface{})
Info 在分组中记录 Info 级别日志
func (*ConsoleGroup) InfoContext ¶
func (cg *ConsoleGroup) InfoContext(ctx context.Context, format string, args ...interface{})
InfoContext 在分组中记录带上下文的 Info 级别日志
func (*ConsoleGroup) Log ¶
func (cg *ConsoleGroup) Log(level LogLevel, format string, args ...interface{})
Log 在当前分组中记录日志
func (*ConsoleGroup) Table ¶
func (cg *ConsoleGroup) Table(data interface{})
Table 在分组中显示表格 类似 JavaScript console.table()
func (*ConsoleGroup) Time ¶
func (cg *ConsoleGroup) Time(label string) *Timer
Time 开始计时 类似 JavaScript console.time()
func (*ConsoleGroup) Warn ¶
func (cg *ConsoleGroup) Warn(format string, args ...interface{})
Warn 在分组中记录 Warn 级别日志
func (*ConsoleGroup) WarnContext ¶
func (cg *ConsoleGroup) WarnContext(ctx context.Context, format string, args ...interface{})
WarnContext 在分组中记录带上下文的 Warn 级别日志
type ConsoleTable ¶
ConsoleTable 表格数据结构
type ConsoleWriterOption ¶
type ConsoleWriterOption func(*consoleLogWriter)
ConsoleWriterOption 控制台输出器配置选项
func WithConsoleBatchBytes ¶
func WithConsoleBatchBytes(bytes int) ConsoleWriterOption
WithConsoleBatchBytes 设置合并写出字节上限(默认 64KB,达到即触发一次合并写出)
func WithConsoleColor ¶
func WithConsoleColor(color bool) ConsoleWriterOption
WithConsoleColor 设置是否启用颜色
func WithConsoleFlushInterval ¶
func WithConsoleFlushInterval(interval time.Duration) ConsoleWriterOption
WithConsoleFlushInterval 设置定时刷写间隔(默认 100ms)
func WithConsoleLevel ¶
func WithConsoleLevel(level LogLevel) ConsoleWriterOption
WithConsoleLevel 设置日志级别
func WithConsoleOutput ¶
func WithConsoleOutput(output io.Writer) ConsoleWriterOption
WithConsoleOutput 设置输出目标
func WithConsoleQueueSize ¶
func WithConsoleQueueSize(bytes int) ConsoleWriterOption
WithConsoleQueueSize 设置待写缓冲的硬上限(字节)
早期实现是按条数限制的队列深度,双缓冲改造后待写量以字节计,故语义改为字节上限: 活动缓冲涨过此值时降级为持锁同步直写,形成背压。<=0 表示按 batchBytes 自动推导
type ContextExtractor ¶
ContextExtractor 上下文信息提取器函数类型
type EmptyAdapter ¶
type EmptyAdapter struct {
*EmptyLogger
// contains filtered or unexported fields
}
EmptyAdapter 是 IAdapter 接口的空实现
func (*EmptyAdapter) GetAdapterName ¶
func (e *EmptyAdapter) GetAdapterName() string
GetAdapterName 获取适配器名称
func (*EmptyAdapter) GetAdapterVersion ¶
func (e *EmptyAdapter) GetAdapterVersion() string
GetAdapterVersion 获取适配器版本
func (*EmptyAdapter) SetHealthy ¶
func (e *EmptyAdapter) SetHealthy(healthy bool)
SetHealthy 设置适配器健康状态
type EmptyHook ¶
type EmptyHook struct {
// contains filtered or unexported fields
}
EmptyHook 是 IHook 接口的空实现
type EmptyLogger ¶
type EmptyLogger struct {
// contains filtered or unexported fields
}
EmptyLogger 是 ILogger 接口的空实现,所有方法都不执行任何操作 常用于测试环境或需要禁用日志输出的场景
func NewEmptyLoggerWithLevel ¶
func NewEmptyLoggerWithLevel(level LogLevel) *EmptyLogger
NewEmptyLoggerWithLevel 创建一个指定级别的空日志实例
func (*EmptyLogger) ConsoleGroup ¶
func (e *EmptyLogger) ConsoleGroup(label string, args ...interface{})
ConsoleGroup 空实现 - 开始分组(不执行任何操作)
func (*EmptyLogger) ConsoleGroupCollapsed ¶
func (e *EmptyLogger) ConsoleGroupCollapsed(label string, args ...interface{})
ConsoleGroupCollapsed 空实现 - 开始折叠分组(不执行任何操作)
func (*EmptyLogger) ConsoleGroupEnd ¶
func (e *EmptyLogger) ConsoleGroupEnd()
ConsoleGroupEnd 空实现 - 结束分组(不执行任何操作)
func (*EmptyLogger) ConsoleTable ¶
func (e *EmptyLogger) ConsoleTable(data interface{})
ConsoleTable 空实现 - 显示表格(不执行任何操作)
func (*EmptyLogger) ConsoleTime ¶
func (e *EmptyLogger) ConsoleTime(label string) *Timer
ConsoleTime 空实现 - 开始计时(返回空的计时器)
func (*EmptyLogger) Debug ¶
func (e *EmptyLogger) Debug(format string, args ...interface{})
基本日志方法 - 所有方法都是空实现
func (*EmptyLogger) DebugContext ¶
func (e *EmptyLogger) DebugContext(ctx context.Context, format string, args ...interface{})
带上下文的日志方法
func (*EmptyLogger) DebugContextKV ¶
func (e *EmptyLogger) DebugContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
带上下文的结构化日志方法
func (*EmptyLogger) DebugContextLines ¶
func (e *EmptyLogger) DebugContextLines(ctx context.Context, lines ...string)
多行日志方法(带上下文)
func (*EmptyLogger) DebugCtxReturn ¶
func (e *EmptyLogger) DebugCtxReturn(ctx context.Context, format string, args ...interface{}) error
返回错误的上下文日志方法
func (*EmptyLogger) DebugKV ¶
func (e *EmptyLogger) DebugKV(msg string, keysAndValues ...interface{})
结构化日志方法(键值对)
func (*EmptyLogger) DebugKVReturn ¶
func (e *EmptyLogger) DebugKVReturn(msg string, keysAndValues ...interface{}) error
返回错误的键值对日志方法
func (*EmptyLogger) DebugLines ¶
func (e *EmptyLogger) DebugLines(lines ...string)
func (*EmptyLogger) DebugReturn ¶
func (e *EmptyLogger) DebugReturn(format string, args ...interface{}) error
返回错误的日志方法
func (*EmptyLogger) DebugWithFields ¶
func (e *EmptyLogger) DebugWithFields(msg string, fields map[string]interface{})
字段映射方法(直接支持 map[string]interface{})
func (*EmptyLogger) Debugf ¶
func (e *EmptyLogger) Debugf(format string, args ...interface{})
Printf风格方法(与上面相同,但命名更明确)
func (*EmptyLogger) Error ¶
func (e *EmptyLogger) Error(format string, args ...interface{})
func (*EmptyLogger) ErrorContext ¶
func (e *EmptyLogger) ErrorContext(ctx context.Context, format string, args ...interface{})
func (*EmptyLogger) ErrorContextKV ¶
func (e *EmptyLogger) ErrorContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
func (*EmptyLogger) ErrorContextLines ¶
func (e *EmptyLogger) ErrorContextLines(ctx context.Context, lines ...string)
func (*EmptyLogger) ErrorCtxReturn ¶
func (e *EmptyLogger) ErrorCtxReturn(ctx context.Context, format string, args ...interface{}) error
func (*EmptyLogger) ErrorKV ¶
func (e *EmptyLogger) ErrorKV(msg string, keysAndValues ...interface{})
func (*EmptyLogger) ErrorKVReturn ¶
func (e *EmptyLogger) ErrorKVReturn(msg string, keysAndValues ...interface{}) error
func (*EmptyLogger) ErrorLines ¶
func (e *EmptyLogger) ErrorLines(lines ...string)
func (*EmptyLogger) ErrorMsg ¶
func (e *EmptyLogger) ErrorMsg(msg string)
func (*EmptyLogger) ErrorReturn ¶
func (e *EmptyLogger) ErrorReturn(format string, args ...interface{}) error
func (*EmptyLogger) ErrorWithFields ¶
func (e *EmptyLogger) ErrorWithFields(msg string, fields map[string]interface{})
func (*EmptyLogger) Errorf ¶
func (e *EmptyLogger) Errorf(format string, args ...interface{})
func (*EmptyLogger) Fatal ¶
func (e *EmptyLogger) Fatal(format string, args ...interface{})
func (*EmptyLogger) FatalContext ¶
func (e *EmptyLogger) FatalContext(ctx context.Context, format string, args ...interface{})
func (*EmptyLogger) FatalContextKV ¶
func (e *EmptyLogger) FatalContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
func (*EmptyLogger) FatalKV ¶
func (e *EmptyLogger) FatalKV(msg string, keysAndValues ...interface{})
func (*EmptyLogger) FatalMsg ¶
func (e *EmptyLogger) FatalMsg(msg string)
func (*EmptyLogger) FatalWithFields ¶
func (e *EmptyLogger) FatalWithFields(msg string, fields map[string]interface{})
func (*EmptyLogger) Fatalf ¶
func (e *EmptyLogger) Fatalf(format string, args ...interface{})
func (*EmptyLogger) GetLevel ¶
func (e *EmptyLogger) GetLevel() LogLevel
func (*EmptyLogger) Info ¶
func (e *EmptyLogger) Info(format string, args ...interface{})
func (*EmptyLogger) InfoContext ¶
func (e *EmptyLogger) InfoContext(ctx context.Context, format string, args ...interface{})
func (*EmptyLogger) InfoContextKV ¶
func (e *EmptyLogger) InfoContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
func (*EmptyLogger) InfoContextLines ¶
func (e *EmptyLogger) InfoContextLines(ctx context.Context, lines ...string)
func (*EmptyLogger) InfoCtxReturn ¶
func (e *EmptyLogger) InfoCtxReturn(ctx context.Context, format string, args ...interface{}) error
func (*EmptyLogger) InfoKV ¶
func (e *EmptyLogger) InfoKV(msg string, keysAndValues ...interface{})
func (*EmptyLogger) InfoKVReturn ¶
func (e *EmptyLogger) InfoKVReturn(msg string, keysAndValues ...interface{}) error
func (*EmptyLogger) InfoMsg ¶
func (e *EmptyLogger) InfoMsg(msg string)
func (*EmptyLogger) InfoReturn ¶
func (e *EmptyLogger) InfoReturn(format string, args ...interface{}) error
func (*EmptyLogger) InfoWithFields ¶
func (e *EmptyLogger) InfoWithFields(msg string, fields map[string]interface{})
func (*EmptyLogger) Infof ¶
func (e *EmptyLogger) Infof(format string, args ...interface{})
func (*EmptyLogger) IsLevelEnabled ¶
func (e *EmptyLogger) IsLevelEnabled(level LogLevel) bool
func (*EmptyLogger) IsShowCaller ¶
func (e *EmptyLogger) IsShowCaller() bool
func (*EmptyLogger) LogContext ¶
func (e *EmptyLogger) LogContext(ctx context.Context, level LogLevel, msg string)
func (*EmptyLogger) LogKV ¶
func (e *EmptyLogger) LogKV(level LogLevel, msg string, keysAndValues ...interface{})
func (*EmptyLogger) LogSpecialContext ¶
func (e *EmptyLogger) LogSpecialContext(ctx context.Context, logType SpecialLogType, level LogLevel, format string, args ...interface{})
特殊类型日志方法(空实现)
func (*EmptyLogger) LogWithFields ¶
func (e *EmptyLogger) LogWithFields(level LogLevel, msg string, fields map[string]interface{})
func (*EmptyLogger) NewConsoleGroup ¶
func (e *EmptyLogger) NewConsoleGroup() *ConsoleGroup
NewConsoleGroup 创建空的 ConsoleGroup(不执行任何操作)
func (*EmptyLogger) Printf ¶
func (e *EmptyLogger) Printf(format string, args ...interface{})
func (*EmptyLogger) Println ¶
func (e *EmptyLogger) Println(args ...interface{})
func (*EmptyLogger) SetShowCaller ¶
func (e *EmptyLogger) SetShowCaller(show bool)
func (*EmptyLogger) Warn ¶
func (e *EmptyLogger) Warn(format string, args ...interface{})
func (*EmptyLogger) WarnContext ¶
func (e *EmptyLogger) WarnContext(ctx context.Context, format string, args ...interface{})
func (*EmptyLogger) WarnContextKV ¶
func (e *EmptyLogger) WarnContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
func (*EmptyLogger) WarnContextLines ¶
func (e *EmptyLogger) WarnContextLines(ctx context.Context, lines ...string)
func (*EmptyLogger) WarnCtxReturn ¶
func (e *EmptyLogger) WarnCtxReturn(ctx context.Context, format string, args ...interface{}) error
func (*EmptyLogger) WarnKV ¶
func (e *EmptyLogger) WarnKV(msg string, keysAndValues ...interface{})
func (*EmptyLogger) WarnKVReturn ¶
func (e *EmptyLogger) WarnKVReturn(msg string, keysAndValues ...interface{}) error
func (*EmptyLogger) WarnLines ¶
func (e *EmptyLogger) WarnLines(lines ...string)
func (*EmptyLogger) WarnMsg ¶
func (e *EmptyLogger) WarnMsg(msg string)
func (*EmptyLogger) WarnReturn ¶
func (e *EmptyLogger) WarnReturn(format string, args ...interface{}) error
func (*EmptyLogger) WarnWithFields ¶
func (e *EmptyLogger) WarnWithFields(msg string, fields map[string]interface{})
func (*EmptyLogger) Warnf ¶
func (e *EmptyLogger) Warnf(format string, args ...interface{})
func (*EmptyLogger) WithContext ¶
func (e *EmptyLogger) WithContext(ctx context.Context) ILogger
func (*EmptyLogger) WithError ¶
func (e *EmptyLogger) WithError(err error) ILogger
func (*EmptyLogger) WithField ¶
func (e *EmptyLogger) WithField(key string, value interface{}) ILogger
结构化日志构建器方法 - 返回自身以保持链式调用
func (*EmptyLogger) WithFields ¶
func (e *EmptyLogger) WithFields(fields map[string]interface{}) ILogger
type EmptyWriter ¶
type EmptyWriter struct {
// contains filtered or unexported fields
}
EmptyWriter 是 IWriter 接口的空实现
func (*EmptyWriter) Write ¶
func (e *EmptyWriter) Write(p []byte) (n int, err error)
Write 写入数据(空实现)
func (*EmptyWriter) WriteLevel ¶
func (e *EmptyWriter) WriteLevel(level LogLevel, data []byte) (n int, err error)
WriteLevel 按级别写入数据(空实现)
type FailureLog ¶
type FailureLog struct {
// contains filtered or unexported fields
}
FailureLog 按"任务 + 错误类别"等键汇总持续失败并写日志,可并发使用
长时间没有新失败的键会被摊销清理且不输出恢复日志,内存只随"正在失败的键数" 增长,不随历史键数增长。
汇总字段 failure_count、suppressed_count、failure_duration_ms 写在调用方 字段之后,故同名时以汇总值为准;单次操作耗时等调用方数据应使用其他字段名
func NewFailureLog ¶
func NewFailureLog(logger ILogger, cfg FailureLogConfig) *FailureLog
NewFailureLog 创建按键失败记录器
func (*FailureLog) Count ¶
func (f *FailureLog) Count(key string) int64
Count 返回 key 当前的连续失败次数,可用于计算退避
type FailureLogConfig ¶
type FailureLogConfig struct {
// Interval、MaxInterval 含义同 FailureState
Interval time.Duration
MaxInterval time.Duration
// IdleTTL 某个键最后一次失败后保留其状态的时长
// <=0 时取 10 分钟与两倍 MaxInterval 中的较大值
IdleTTL time.Duration
// Now 供测试替换时钟
Now func() time.Time
}
FailureLogConfig 按键失败记录器的配置
type FailureState ¶
type FailureState struct {
// Interval 汇总间隔,<=0 时取 DefaultFailureInterval
Interval time.Duration
// MaxInterval 大于 Interval 时,每输出一条后间隔翻倍直至该上限
// 用于长时间卡死的依赖:故障初期密集反馈,持续故障后逐步稀释
MaxInterval time.Duration
// contains filtered or unexported fields
}
FailureState 单个失败源的限频状态
零值即可用(间隔取 DefaultFailureInterval)。只保存常量大小的状态, 并发保护与实际写日志由调用方负责——需要开箱即用的并发安全版本见 FailureLog
type FileLogWriter ¶
type FileLogWriter struct {
// contains filtered or unexported fields
}
FileLogWriter 文件输出器(支持可配置缓冲区大小)
func (*FileLogWriter) GetStats ¶
func (w *FileLogWriter) GetStats() WriterStatsSnapshot
GetStats 获取统计信息
func (*FileLogWriter) IsHealthy ¶
func (w *FileLogWriter) IsHealthy() bool
IsHealthy 检查健康状态(使用 atomic 快速检查)
func (*FileLogWriter) Write ¶
func (w *FileLogWriter) Write(p []byte) (n int, err error)
Write 实现io.Writer接口(写入缓冲区)
func (*FileLogWriter) WriteLevel ¶
func (w *FileLogWriter) WriteLevel(level LogLevel, data []byte) (n int, err error)
WriteLevel 按级别写入
type FileWriterOption ¶
type FileWriterOption func(*FileLogWriter)
FileWriterOption 文件输出器配置选项
func WithFileBufferSize ¶
func WithFileBufferSize(size int) FileWriterOption
WithFileBufferSize 设置缓冲区大小(字节)
func WithFilePermission ¶
func WithFilePermission(permission os.FileMode) FileWriterOption
WithFilePermission 设置文件权限
func WithFileWriterPath ¶
func WithFileWriterPath(filePath string) FileWriterOption
WithFileWriterPath 设置文件路径
type FormatType ¶
type FormatType string
FormatType 输出格式类型
const ( FormatText FormatType = "text" FormatJSON FormatType = "json" FormatXML FormatType = "xml" FormatCSV FormatType = "csv" )
type IAdapter ¶
type IAdapter interface {
ILogger
// 生命周期管理
Initialize() error
Close() error
Flush() error
// 适配器特定功能
GetAdapterName() string
GetAdapterVersion() string
IsHealthy() bool
}
IAdapter 日志适配器接口
type IAdvancedLogger ¶
type IAdvancedLogger interface {
ILogger
// 采样和限流
Sample(every int) ILogger
RateLimit(rate float64) ILogger
// 异步日志
Async() ILogger
Sync() error
// 缓冲控制
Buffer(size int) ILogger
Flush() error
// 条件日志
If(condition bool) ILogger
Unless(condition bool) ILogger
}
高级日志功能接口
type IFileWriter ¶
type IFileWriter interface {
io.WriteCloser
// 文件管理
Rotate() error
GetCurrentFile() string
GetFileSize() int64
// 配置
SetMaxSize(size int64)
SetMaxBackups(backups int)
SetMaxAge(days int)
SetCompress(compress bool)
}
IFileWriter 文件写入器接口
type IFormatter ¶
IFormatter 日志格式化器接口
type IFrameworkAdapter ¶
type IFrameworkAdapter interface {
ILogger
// 框架检测
GetFrameworkName() string
GetFrameworkVersion() string
// 原生框架实例
GetNativeLogger() interface{}
// 配置同步
SyncConfig() error
}
通用日志适配器接口
type ILogBuilder ¶
type ILogBuilder interface {
Level(level LogLevel) ILogBuilder
Message(msg string) ILogBuilder
Field(key string, value interface{}) ILogBuilder
Fields(fields map[string]interface{}) ILogBuilder
Error(err error) ILogBuilder
Context(ctx context.Context) ILogBuilder
Caller(skip int) ILogBuilder
Timestamp(t interface{}) ILogBuilder
Build() *LogEntry
Log()
}
构建器模式接口
type ILogger ¶
type ILogger interface {
// 基本日志方法(Printf风格)
Debug(format string, args ...interface{})
Info(format string, args ...interface{})
Warn(format string, args ...interface{})
Error(format string, args ...interface{})
Fatal(format string, args ...interface{})
// Printf风格日志方法(与上面相同,但命名更明确)
Debugf(format string, args ...interface{})
Infof(format string, args ...interface{})
Warnf(format string, args ...interface{})
Errorf(format string, args ...interface{})
Fatalf(format string, args ...interface{})
// 纯文本日志方法(支持单个消息)
DebugMsg(msg string)
InfoMsg(msg string)
WarnMsg(msg string)
ErrorMsg(msg string)
FatalMsg(msg string)
// 返回错误的日志方法(记录日志并返回错误)
DebugReturn(format string, args ...interface{}) error
InfoReturn(format string, args ...interface{}) error
WarnReturn(format string, args ...interface{}) error
ErrorReturn(format string, args ...interface{}) error
// 返回错误的上下文日志方法
DebugCtxReturn(ctx context.Context, format string, args ...interface{}) error
InfoCtxReturn(ctx context.Context, format string, args ...interface{}) error
WarnCtxReturn(ctx context.Context, format string, args ...interface{}) error
ErrorCtxReturn(ctx context.Context, format string, args ...interface{}) error
// 返回错误的键值对日志方法
DebugKVReturn(msg string, keysAndValues ...interface{}) error
InfoKVReturn(msg string, keysAndValues ...interface{}) error
WarnKVReturn(msg string, keysAndValues ...interface{}) error
ErrorKVReturn(msg string, keysAndValues ...interface{}) error
// 带上下文的日志方法
DebugContext(ctx context.Context, format string, args ...interface{})
InfoContext(ctx context.Context, format string, args ...interface{})
WarnContext(ctx context.Context, format string, args ...interface{})
ErrorContext(ctx context.Context, format string, args ...interface{})
FatalContext(ctx context.Context, format string, args ...interface{})
// 结构化日志方法(键值对)
DebugKV(msg string, keysAndValues ...interface{})
InfoKV(msg string, keysAndValues ...interface{})
WarnKV(msg string, keysAndValues ...interface{})
ErrorKV(msg string, keysAndValues ...interface{})
FatalKV(msg string, keysAndValues ...interface{})
// 结构化日志方法(字段映射)- 直接支持 map[string]interface{}
DebugWithFields(msg string, fields map[string]interface{})
InfoWithFields(msg string, fields map[string]interface{})
WarnWithFields(msg string, fields map[string]interface{})
ErrorWithFields(msg string, fields map[string]interface{})
FatalWithFields(msg string, fields map[string]interface{})
// 带上下文的结构化日志方法(键值对)
DebugContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
InfoContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
WarnContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
ErrorContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
FatalContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
// 多行日志方法(自动处理多行格式)
InfoLines(lines ...string)
ErrorLines(lines ...string)
WarnLines(lines ...string)
DebugLines(lines ...string)
// 多行日志方法(带上下文,每一行均附加 ctx 中的 trace 等信息)
DebugContextLines(ctx context.Context, lines ...string)
InfoContextLines(ctx context.Context, lines ...string)
WarnContextLines(ctx context.Context, lines ...string)
ErrorContextLines(ctx context.Context, lines ...string)
// 原始日志条目方法(最灵活)
Log(level LogLevel, msg string)
LogContext(ctx context.Context, level LogLevel, msg string)
LogKV(level LogLevel, msg string, keysAndValues ...interface{})
LogWithFields(level LogLevel, msg string, fields map[string]interface{})
// 特殊类型日志方法(带 context,支持 emoji 分类日志)
LogSpecialContext(ctx context.Context, logType SpecialLogType, level LogLevel, format string, args ...interface{})
// 配置方法
SetLevel(level LogLevel)
GetLevel() LogLevel
SetShowCaller(show bool)
IsShowCaller() bool
IsLevelEnabled(level LogLevel) bool
// 结构化日志构建器
WithField(key string, value interface{}) ILogger
WithFields(fields map[string]interface{}) ILogger
WithError(err error) ILogger
WithContext(ctx context.Context) ILogger
// 实用方法
Print(args ...interface{}) // 兼容标准log包
Printf(format string, args ...interface{}) // 兼容标准log包
Println(args ...interface{}) // 兼容标准log包
// Console 风格日志功能
NewConsoleGroup() *ConsoleGroup // 创建控制台分组
ConsoleGroup(label string, args ...interface{}) // 开始日志分组
ConsoleGroupCollapsed(label string, args ...interface{}) // 开始折叠分组
ConsoleGroupEnd() // 结束当前分组
ConsoleTable(data interface{}) // 显示表格
ConsoleTime(label string) *Timer // 开始计时
}
ILogger 增强的日志记录器接口,支持多种参数格式
var ( // NoLogger 全局的空日志实例,用于禁用所有日志输出 NoLogger ILogger = NewEmptyLogger() // DiscardLogger 废弃所有日志的实例,与NoLogger功能相同 DiscardLogger ILogger = NewEmptyLogger() // NullLogger 空日志实例,用于测试场景 NullLogger ILogger = NewEmptyLogger() )
全局空日志实例
func WrapWithEmpty ¶
WrapWithEmpty 将任何日志器包装为空实现(用于临时禁用日志)
type ILogrusLogger ¶
type ILogrusLogger interface {
// Logrus特有方法
Trace(args ...interface{})
}
ILogrusLogger Logrus日志框架兼容接口
type IManager ¶
type IManager interface {
// 适配器管理
AddAdapter(name string, adapter IAdapter) error
GetAdapter(name string) (IAdapter, bool)
RemoveAdapter(name string) error
ListAdapters() []string
// 生命周期管理
CloseAll() error
FlushAll() error
// 全局设置
SetLevelAll(level LogLevel)
Broadcast(level LogLevel, format string, args ...interface{})
// 健康检查
HealthCheck() map[string]bool
}
IManager 日志管理器接口
type IMiddleware ¶
type IMiddleware interface {
Process(entry *LogEntry, next func(*LogEntry) error) error
GetName() string
GetPriority() int
}
IMiddleware 日志中间件接口
type ISlogLogger ¶
type ISlogLogger interface {
// slog特有方法
LogAttrs(ctx context.Context, level LogLevel, msg string, attrs ...interface{})
With(args ...interface{}) ISlogLogger
WithGroup(name string) ISlogLogger
}
ISlogLogger 标准库slog兼容接口
type IWriter ¶
type IWriter interface {
io.Writer
// 写入控制
WriteLevel(level LogLevel, data []byte) (n int, err error)
Flush() error
Close() error
// 状态查询
IsHealthy() bool
GetStats() WriterStatsSnapshot
}
IWriter 日志写入器接口
func CreateWriter ¶
func CreateWriter(config *WriterConfig) (IWriter, error)
CreateWriter 根据配置创建 Writer
func DefaultOutput ¶
func DefaultOutput() IWriter
DefaultOutput 返回默认输出目标:共享的 stdout 异步批量输出器 首次调用时惰性构造(启动后台 flusher),后续调用返回同一实例
func NewBufferedWriter ¶
func NewBufferedWriter(opts ...BufferedWriterOption) IWriter
NewBufferedWriter 创建缓冲输出器
func NewConsoleWriter ¶
func NewConsoleWriter(opts ...ConsoleWriterOption) IWriter
NewConsoleWriter 创建控制台输出器(内建异步批量管道,构造时启动后台 flusher)
func NewRotateWriter ¶
func NewRotateWriter(opts ...RotateWriterOption) IWriter
NewRotateWriter 创建轮转文件输出器
func StderrOutput ¶
func StderrOutput() IWriter
StderrOutput 返回共享的 stderr 异步批量输出器 首次调用时惰性构造(启动后台 flusher),后续调用返回同一实例
type IZapLogger ¶
type IZapLogger interface {
// Zap特有方法
DPanic(msg string, fields ...interface{})
Sync() error
Sugar() ILogger
}
IZapLogger Zap日志框架兼容接口
type IZerologLogger ¶
type IZerologLogger interface {
// Zerolog链式方法
Str(key, val string) IZerologLogger
Int(key string, i int) IZerologLogger
Float64(key string, f float64) IZerologLogger
Bool(key string, b bool) IZerologLogger
Time(key string, t interface{}) IZerologLogger
Dur(key string, d interface{}) IZerologLogger
Msg(msg string)
Msgf(format string, v ...interface{})
}
IZerologLogger Zerolog兼容接口
type LevelInfo ¶
type LevelInfo struct {
Name string `json:"name"` // 级别名称
ShortName string `json:"short_name"` // 短名称
Emoji string `json:"emoji"` // 表情符号
Color string `json:"color"` // 颜色代码
Priority int `json:"priority"` // 优先级
Description string `json:"description"` // 描述
Category string `json:"category"` // 类别
}
LevelInfo 级别信息结构
type LogArgs ¶
type LogArgs struct {
Format string
Args []interface{}
Fields map[string]interface{}
Context context.Context
}
日志参数辅助类型
type LogEntry ¶
type LogEntry struct {
Level LogLevel `json:"level"`
Message string `json:"message"`
Timestamp int64 `json:"timestamp"`
Fields map[string]interface{} `json:"fields,omitempty"`
Caller *CallerInfo `json:"caller,omitempty"`
}
LogEntry 日志条目
type LogLevel ¶
type LogLevel int
LogLevel 日志级别类型 (保持向后兼容)
const ( DEBUG LogLevel = iota // 调试级别 - 最详细的信息 INFO // 信息级别 - 一般信息 WARN // 警告级别 - 警告信息 ERROR // 错误级别 - 错误信息 FATAL // 致命级别 - 致命错误,程序将退出 )
基础日志级别常量 (保持现有API兼容性)
扩展级别常量 (新增的高级功能)
const ( SYSTEM LogLevel = 100 + iota // 系统级信息 KERNEL // 内核级信息 DRIVER // 驱动级信息 APPLICATION // 应用级信息 SERVICE // 服务级信息 COMPONENT // 组件级信息 MODULE // 模块级信息 )
系统级扩展级别
const ( BUSINESS LogLevel = 200 + iota // 业务级信息 TRANSACTION // 事务级信息 WORKFLOW // 工作流信息 PROCESS // 流程级信息 )
业务级扩展级别
const ( SECURITY LogLevel = 300 + iota // 安全级信息 AUDIT // 审计级信息 COMPLIANCE // 合规级信息 THREAT // 威胁级信息 )
安全级扩展级别
const ( PERFORMANCE LogLevel = 400 + iota // 性能级信息 METRIC // 指标级信息 BENCHMARK // 基准测试信息 PROFILING // 性能分析信息 )
性能级扩展级别
func GetAllExtendedLevels ¶
func GetAllExtendedLevels() []LogLevel
GetAllExtendedLevels 获取所有级别(包括扩展级别)
func GetLevelsByCategory ¶
GetLevelsByCategory 根据类别获取级别
func (LogLevel) MarshalText ¶
MarshalText 实现文本序列化(用于 JSON 等)
func (*LogLevel) UnmarshalText ¶
UnmarshalText 实现文本反序列化(用于 JSON 等)
func (*LogLevel) UnmarshalYAML ¶
UnmarshalYAML 实现 YAML 反序列化,支持字符串和整数值
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger 主要的日志记录器结构体
func NewLogger ¶
func NewLogger() *Logger
NewLogger 创建新的日志记录器(默认配置)
默认输出为共享的 stdout 异步批量输出器(见 stdout.go 的成本实测与权衡), 而非裸 os.Stdout:后者每条日志一次 syscall + 一次互斥,占全链路 85~97% 的成本 异步语义要求优雅退出时调用 Flush();需要逐条立即落盘时用 WithOutput(os.Stdout) 退回裸流
着色默认随输出目标自动判定(终端开、重定向关),不再无条件开启
func (*Logger) ConsoleGroup ¶
ConsoleGroup 开始一个新的日志分组
func (*Logger) ConsoleGroupCollapsed ¶
ConsoleGroupCollapsed 开始一个折叠的日志分组
func (*Logger) DebugContext ¶
带上下文的日志方法
func (*Logger) DebugContextKV ¶
func (*Logger) DebugContextLines ¶
多行日志方法(带上下文)
func (*Logger) DebugCtxReturn ¶
DebugCtxReturn 记录带上下文的调试日志并返回格式化的错误
func (*Logger) DebugKVReturn ¶
DebugKVReturn 记录带键值对的调试日志并返回错误
func (*Logger) DebugLines ¶
func (*Logger) DebugReturn ¶
DebugReturn 记录调试日志并返回格式化的错误
func (*Logger) DebugWithFields ¶
字段映射方法(直接支持 map[string]any)
func (*Logger) Environment ¶
Environment 环境日志(INFO 级别)
func (*Logger) ErrorContext ¶
func (*Logger) ErrorContextKV ¶
func (*Logger) ErrorContextLines ¶
func (*Logger) ErrorCtxReturn ¶
ErrorCtxReturn 记录带上下文的错误日志并返回格式化的错误
func (*Logger) ErrorKVReturn ¶
ErrorKVReturn 记录带键值对的错误日志并返回错误
func (*Logger) ErrorLines ¶
func (*Logger) ErrorReturn ¶
ErrorReturn 记录错误日志并返回格式化的错误
func (*Logger) ErrorWithFields ¶
func (*Logger) FatalContext ¶
func (*Logger) FatalContextKV ¶
func (*Logger) FatalWithFields ¶
func (*Logger) Flush ¶
Flush 刷新输出目标中缓冲的日志条目 异步输出器(控制台批量管道)在优雅退出链路中调用此方法, 确保 SIGTERM/SIGINT 时队列中的日志不丢失
func (*Logger) GetContextExtractor ¶
func (l *Logger) GetContextExtractor() ContextExtractor
GetContextExtractor 获取当前的上下文提取器
func (*Logger) InfoContext ¶
func (*Logger) InfoContextKV ¶
func (*Logger) InfoContextLines ¶
func (*Logger) InfoCtxReturn ¶
InfoCtxReturn 记录带上下文的信息日志并返回格式化的错误
func (*Logger) InfoKVReturn ¶
InfoKVReturn 记录带键值对的信息日志并返回错误
func (*Logger) InfoReturn ¶
InfoReturn 记录信息日志并返回格式化的错误
func (*Logger) IsLevelEnabled ¶
IsLevelEnabled 检查给定级别是否启用
func (*Logger) LogContext ¶
func (*Logger) LogSpecialContext ¶
func (l *Logger) LogSpecialContext(ctx context.Context, logType SpecialLogType, level LogLevel, format string, args ...any)
LogSpecialContext 记录带上下文的特殊类型日志(公开方法)
使用示例:
logger.LogSpecialContext(ctx, SuccessType, INFO, "操作成功") logger.LogSpecialContext(ctx, DatabaseType, INFO, "查询 %s 耗时 %v", table, duration) logger.LogSpecialContext(ctx, SecurityType, SECURITY, "检测到异常访问 %s", ip)
JSON 模式:ctx 字段提取到 JSON fields;text 模式:ctx 信息前缀到消息
func (*Logger) LogWithFields ¶
func (*Logger) NewConsoleGroup ¶
func (l *Logger) NewConsoleGroup() *ConsoleGroup
NewConsoleGroup 创建新的控制台分组 继承 logger 的 output(可能是 buffer/stdout/文件),但不走 logger 格式化
func (*Logger) Performance ¶
Performance 性能日志(PERFORMANCE 级别,支持可选的详细信息)
func (*Logger) SetContextExtractor ¶
func (l *Logger) SetContextExtractor(extractor ContextExtractor)
SetContextExtractor 设置自定义上下文提取器
func (*Logger) StartTiming ¶
StartTiming 开始计时
func (*Logger) WarnContext ¶
func (*Logger) WarnContextKV ¶
func (*Logger) WarnContextLines ¶
func (*Logger) WarnCtxReturn ¶
WarnCtxReturn 记录带上下文的警告日志并返回格式化的错误
func (*Logger) WarnKVReturn ¶
WarnKVReturn 记录带键值对的警告日志并返回错误
func (*Logger) WarnReturn ¶
WarnReturn 记录警告日志并返回格式化的错误
func (*Logger) WithCallerDepth ¶
WithCallerDepth 设置调用者深度
func (*Logger) WithCallerKey ¶
WithCallerKey 设置调用者字段名
func (*Logger) WithColorful ¶
WithColorful 设置是否使用彩色输出 显式调用后不再随输出目标自动判定,始终尊重此处的选择
func (*Logger) WithContext ¶
WithContext 带上下文的logger(当前实现返回自身)
func (*Logger) WithContextExtractor ¶
func (l *Logger) WithContextExtractor(extractor ContextExtractor) *Logger
WithContextExtractor 设置上下文提取器
func (*Logger) WithContextKeys ¶
WithContextKeys 配置 Logger 在记录 Context 日志时提取哪些 key
func (*Logger) WithField ¶
WithField 添加字段信息(结构化日志) 字段在此处一次性预编码,子 Logger 后续每条日志只做一次 memcpy(见 fields.go)
func (*Logger) WithFields ¶
WithFields 添加多个字段信息(结构化日志) 字段按键排序后预编码,保证同一子 Logger 打出的 JSON 字段顺序稳定
func (*Logger) WithFormat ¶
func (l *Logger) WithFormat(format FormatType) *Logger
WithFormat 设置输出格式
func (*Logger) WithFormatter ¶
func (l *Logger) WithFormatter(formatter IFormatter) *Logger
WithFormatter 设置格式化器
func (*Logger) WithInstance ¶
WithInstance 设置实例标识(输出为 instance 字段) 传空串表示按 INSTANCE_ID / POD_NAME / HOSTNAME 依次推导,都取不到时回落到主机名
func (*Logger) WithLevelKey ¶
WithLevelKey 设置日志级别字段名
func (*Logger) WithMaxFieldBytes ¶
WithMaxFieldBytes 设置单个字段值的字节上限,<=0 表示不限制(默认)
默认不限制:通用日志库静默截断调用方的数据是意外行为,应由调用方按业务 明确选择。整行上限(默认开启)已能兜住失控的大 payload
func (*Logger) WithMaxLineBytes ¶
WithMaxLineBytes 设置单条日志的字节上限,<=0 表示不限制 上限不含末尾换行;超限时条目会补 truncated 标记
func (*Logger) WithMessageKey ¶
WithMessageKey 设置消息字段名
func (*Logger) WithMiddleware ¶
func (l *Logger) WithMiddleware(middleware []IMiddleware) *Logger
WithMiddleware 设置中间件列表
func (*Logger) WithOutput ¶
WithOutput 设置输出目标
output 原样使用,不做缓冲/异步包装:需要高吞吐时传入内置输出器 (NewConsoleWriter / NewFileWriter / NewRotateWriter / DefaultOutput), 传入裸 os.Stdout 或 *os.File 即明确选择"逐条立即落盘"的同步语义
未显式调用过 WithColorful 时,着色随新目标的能力重新判定
func (*Logger) WithSanitize ¶
func (l *Logger) WithSanitize(mode SanitizeMode) *Logger
WithSanitize 设置脱敏强度(默认 SanitizeKeys)
func (*Logger) WithService ¶
WithService 设置服务名(输出为 service 字段)
func (*Logger) WithShowCaller ¶
WithShowCaller 设置是否显示调用者信息
func (*Logger) WithShowStacktrace ¶
WithShowStacktrace 设置是否显示堆栈跟踪
func (*Logger) WithStacktraceKey ¶
WithStacktraceKey 设置堆栈跟踪字段名
func (*Logger) WithTimeFormat ¶
WithTimeFormat 设置时间格式
func (*Logger) WithTimestampKey ¶
WithTimestampKey 设置时间戳字段名(条目首字段,片段不带前导逗号)
func (*Logger) WithWriters ¶
WithWriters 设置写入器列表
type LoggerStats ¶
type LoggerStats struct {
StartTime time.Time `json:"start_time"`
TotalLogs int64 `json:"total_logs"`
LevelCounts map[LogLevel]int64 `json:"level_counts"`
ErrorCount int64 `json:"error_count"`
LastLogTime time.Time `json:"last_log_time"`
Uptime time.Duration `json:"uptime"`
BytesWritten int64 `json:"bytes_written"`
// contains filtered or unexported fields
}
LoggerStats 日志统计信息
func (*LoggerStats) IncrementLevel ¶
func (s *LoggerStats) IncrementLevel(level LogLevel)
IncrementLevel 增加级别计数
type MultiLogWriter ¶
type MultiLogWriter struct {
// contains filtered or unexported fields
}
MultiLogWriter 多输出器(同时写入多个输出器,实现日志分发)
func (*MultiLogWriter) GetStats ¶
func (w *MultiLogWriter) GetStats() WriterStatsSnapshot
GetStats 获取统计信息
func (*MultiLogWriter) IsHealthy ¶
func (w *MultiLogWriter) IsHealthy() bool
IsHealthy 检查是否至少有一个输出器健康
func (*MultiLogWriter) Write ¶
func (w *MultiLogWriter) Write(p []byte) (n int, err error)
Write 实现io.Writer接口
func (*MultiLogWriter) WriteLevel ¶
func (w *MultiLogWriter) WriteLevel(level LogLevel, data []byte) (n int, err error)
WriteLevel 按级别写入
type OutputType ¶
type OutputType string
OutputType 输出类型
const ( OutputConsole OutputType = "console" // 控制台输出 OutputFile OutputType = "file" // 文件输出 OutputRotate OutputType = "rotate" // 轮转文件输出 OutputStdout OutputType = "stdout" // 标准输出 OutputStderr OutputType = "stderr" // 标准错误输出 )
type PerformanceLevel ¶
PerformanceLevel 性能级别定义
type RotateLogWriter ¶
type RotateLogWriter struct {
// contains filtered or unexported fields
}
RotateLogWriter 轮转文件输出器(支持按大小自动轮转,支持可配置缓冲区)
func (*RotateLogWriter) GetStats ¶
func (w *RotateLogWriter) GetStats() WriterStatsSnapshot
GetStats 获取统计信息
func (*RotateLogWriter) IsHealthy ¶
func (w *RotateLogWriter) IsHealthy() bool
IsHealthy 检查健康状态(使用 atomic 快速检查)
func (*RotateLogWriter) Write ¶
func (w *RotateLogWriter) Write(p []byte) (n int, err error)
Write 实现io.Writer接口(写入缓冲区)
func (*RotateLogWriter) WriteLevel ¶
func (w *RotateLogWriter) WriteLevel(level LogLevel, data []byte) (n int, err error)
WriteLevel 按级别写入
type RotateWriterOption ¶
type RotateWriterOption func(*RotateLogWriter)
RotateWriterOption 轮转文件输出器配置选项
func WithRotateBufferSize ¶
func WithRotateBufferSize(size int) RotateWriterOption
WithRotateBufferSize 设置缓冲区大小(字节)
func WithRotateLevel ¶
func WithRotateLevel(level LogLevel) RotateWriterOption
WithRotateLevel 设置日志级别
func WithRotatePermission ¶
func WithRotatePermission(permission os.FileMode) RotateWriterOption
WithRotatePermission 设置文件权限
type SanitizeMode ¶
type SanitizeMode int32
SanitizeMode 脱敏强度
const ( // SanitizeOff 关闭脱敏 SanitizeOff SanitizeMode = iota // SanitizeKeys 仅按字段名脱敏(默认) // // 判定全程零分配:规范 snake_case 字段名一次查表命中,非规范形态由后缀扫描 // 边归一化边比较,两者都落空才退回栈上缓冲做一次完整归一化后重查 // 不读取值内容,因此既不会误伤业务正文,成本也不随消息长度增加 SanitizeKeys // SanitizeKeysAndValues 字段名 + 值内容扫描 // // 额外在 msg 与各字段值里查找凭据、JWT、邮箱、手机号与带签名的私有链接 // 代价是每条日志都要扫一遍文本,且业务正文可能被误伤(如长订单号被当成手机号),故不作为默认值 SanitizeKeysAndValues )
type SpecialLogType ¶
type SpecialLogType struct {
// contains filtered or unexported fields
}
SpecialLogType 特殊日志类型
type Timer ¶
type Timer struct {
// contains filtered or unexported fields
}
Timer 计时器 输出直接写入 output(默认 os.Stdout),不走 logger 格式化
func NewTimer ¶
NewTimer 创建新的计时器 output 为输出目标,传入 nil 则使用 os.Stdout 注意:如果多个 Timer 共享同一个 io.Writer,该 Writer 必须是线程安全的(如 os.Stdout)
type Timing ¶
type Timing struct {
// contains filtered or unexported fields
}
Timing 计时器辅助结构
type WriterConfig ¶
type WriterConfig struct {
Type OutputType `json:"type" yaml:"type"` // 输出类型
FilePath string `json:"file_path" yaml:"file_path"` // 文件路径
MaxSize int64 `json:"max_size" yaml:"max_size"` // 最大文件大小(字节)
MaxFiles int `json:"max_files" yaml:"max_files"` // 最大文件数
MaxAge int `json:"max_age" yaml:"max_age"` // 最大保存天数
Compress bool `json:"compress" yaml:"compress"` // 是否压缩
Permission os.FileMode `json:"permission" yaml:"permission"` // 文件权限
BufferSize int `json:"buffer_size" yaml:"buffer_size"` // 缓冲区大小
Output io.Writer `json:"-" yaml:"-"` // 自定义输出
}
WriterConfig Writer 配置
type WriterStatsSnapshot ¶
type WriterStatsSnapshot struct {
BytesWritten int64 `json:"bytes_written"` // 已写入字节总数
LinesWritten int64 `json:"lines_written"` // 已写入行数总数
ErrorCount int64 `json:"error_count"` // 错误次数总数
LastWrite time.Time `json:"last_write"` // 最后一次写入时间
StartTime time.Time `json:"start_time"` // 输出器启动时间
Uptime time.Duration `json:"uptime"` // 运行时长
}
WriterStatsSnapshot 统计信息快照(用于外部访问的只读数据)