Documentation
¶
Index ¶
- Constants
- Variables
- func Debug(args ...interface{})
- func Debugf(template string, args ...interface{})
- func Error(args ...interface{})
- func Errorf(template string, args ...interface{})
- func Fatal(args ...interface{})
- func Fatalf(template string, args ...interface{})
- func Info(args ...interface{})
- func Infof(template string, args ...interface{})
- func Init(opts ...Option) error
- func ListAdapters() []string
- func Log(level Level, v ...interface{})
- func Logf(level Level, format string, v ...interface{})
- func NewContext(ctx context.Context, l *Helper) context.Context
- func RegisterAdapter(name string, factory AdapterFactory)
- func String() string
- func Trace(args ...interface{})
- func Tracef(template string, args ...interface{})
- func V(lvl Level, log Logger) bool
- func Warn(args ...interface{})
- func Warnf(template string, args ...interface{})
- type AdapterConfig
- type AdapterFactory
- type AsyncConfig
- type AsyncPluginConfig
- type CallerHook
- type Config
- type ConsoleConfig
- type ConsoleFormatter
- type CoreConfig
- type ElasticsearchHook
- type Field
- func Any(key string, val interface{}) Field
- func Bool(key string, val bool) Field
- func ClientIP(val string) Field
- func Duration(key string, val time.Duration) Field
- func FieldError(err error) Field
- func FieldString(key string, val string) Field
- func Int(key string, val int) Field
- func Int64(key string, val int64) Field
- func Latency(val time.Duration) Field
- func Method(val string) Field
- func RequestID(val string) Field
- func StatusCode(val int) Field
- func Time(key string, val time.Time) Field
- func TraceID(val string) Field
- func URI(val string) Field
- func UserID(val int64) Field
- type FieldType
- type FileConfig
- type Helper
- func (h *Helper) Debug(args ...interface{})
- func (h *Helper) Debugf(template string, args ...interface{})
- func (h *Helper) Debugw(msg string, keysAndValues ...interface{})
- func (h *Helper) Error(args ...interface{})
- func (h *Helper) Errorf(template string, args ...interface{})
- func (h *Helper) Errorw(msg string, keysAndValues ...interface{})
- func (h *Helper) Fatal(args ...interface{})
- func (h *Helper) Fatalf(template string, args ...interface{})
- func (h *Helper) Info(args ...interface{})
- func (h *Helper) Infof(template string, args ...interface{})
- func (h *Helper) Infow(msg string, keysAndValues ...interface{})
- func (h *Helper) Trace(args ...interface{})
- func (h *Helper) Tracef(template string, args ...interface{})
- func (h *Helper) Warn(args ...interface{})
- func (h *Helper) Warnf(template string, args ...interface{})
- func (h *Helper) Warnw(msg string, keysAndValues ...interface{})
- func (h *Helper) WithError(err error) *Helper
- func (h *Helper) WithFields(fields map[string]interface{}) *Helper
- type LegacyConfig
- type Level
- type Logger
- func Fields(fields map[string]interface{}) Logger
- func NewAsyncLogger(logger Logger, config AsyncConfig) Logger
- func NewDevelopmentLogger() Logger
- func NewFromConfig(cfg *Config) (Logger, error)
- func NewLogger(opts ...Option) Logger
- func NewLogrusLogger(opts ...Option) Logger
- func NewProductionLogger(logPath string) Logger
- func NewSamplingLogger(logger Logger, config SamplingConfig) Logger
- func NewSanitizerLogger(logger Logger, config SanitizerConfig) Logger
- func NewTestLogger() Logger
- func NewZapLogger(opts ...Option) Logger
- func SetupLogger(cfg interface{}) Logger
- type LogrusConfig
- type MetricsHook
- type MetricsPluginConfig
- type NetworkConfig
- type Option
- func SetOption(k, v interface{}) Option
- func WithAsync(config AsyncConfig) Option
- func WithCallerSkipCount(c int) Option
- func WithFields(fields map[string]interface{}) Option
- func WithLevel(level Level) Option
- func WithName(name string) Option
- func WithOutput(out io.Writer) Option
- func WithPath(path string) Option
- func WithSampling(config SamplingConfig) Option
- func WithSanitizer(config SanitizerConfig) Option
- func WithStdout(enabled bool) Option
- type Options
- type OutputConfig
- type PluginsConfig
- type SamplingConfig
- type SamplingPluginConfig
- type SanitizePluginConfig
- type SanitizeRule
- type SanitizerConfig
- type SanitizerRule
- type SentryHook
- type TracingPluginConfig
- type ZapConfig
- type ZapSamplingConfig
- type ZerologConfig
Examples ¶
Constants ¶
const ( // 控制符 Reset = "\033[0m" // 基础颜色(用于日志级别、路径等) Red = "\033[31m" Green = "\033[32m" Yellow = "\033[33m" Blue = "\033[34m" // Caller 路径、GORM 路径 Magenta = "\033[35m" Cyan = "\033[36m" White = "\033[37m" Gray = "\033[90m" // 次要信息 BrightWhite = "\033[97m" // DEBUG 级别 // 加粗颜色(用于高优先级信息) BlueBold = "\033[34;1m" // GORM rows 计数 MagentaBold = "\033[35;1m" RedBold = "\033[31;1m" // FATAL/PANIC YellowBold = "\033[33;1m" GreenBold = "\033[32;1m" CyanBold = "\033[36;1m" )
ANSI 颜色常量(与 GORM 一致) 设计原则:深色背景优化,清晰可读,专业简洁
Variables ¶
var DefaultAsyncConfig = AsyncConfig{ BufferSize: 10000, FlushInterval: 100 * time.Millisecond, DropPolicy: "drop", OnDropped: nil, }
DefaultAsyncConfig 默认异步配置(生产环境推荐)
var DefaultSamplingConfig = SamplingConfig{ Initial: 10, Thereafter: 100, Tick: time.Second, }
DefaultSamplingConfig 默认采样配置(生产环境推荐)
var DefaultSanitizerConfig = SanitizerConfig{ Enabled: true, Rules: DefaultSanitizerRules, }
DefaultSanitizerConfig 默认脱敏配置
var DefaultSanitizerRules = []SanitizerRule{
{
FieldPattern: "phone",
Strategy: "mask",
MaskChar: "*",
KeepPrefix: 3,
KeepSuffix: 4,
},
{
FieldPattern: "idcard",
Strategy: "mask",
MaskChar: "*",
KeepPrefix: 3,
KeepSuffix: 4,
},
{
FieldPattern: "id_card",
Strategy: "mask",
MaskChar: "*",
KeepPrefix: 3,
KeepSuffix: 4,
},
{
FieldPattern: "password",
Strategy: "remove",
},
{
FieldPattern: "passwd",
Strategy: "remove",
},
{
FieldPattern: "token",
Strategy: "hash",
},
{
FieldPattern: "*_token",
Strategy: "hash",
},
{
FieldPattern: "api_key",
Strategy: "hash",
},
{
FieldPattern: "apikey",
Strategy: "hash",
},
{
FieldPattern: "email",
Strategy: "mask",
MaskChar: "*",
KeepPrefix: 4,
KeepSuffix: 12,
},
}
DefaultSanitizerRules 默认脱敏规则(生产环境推荐)
Functions ¶
func NewContext ¶
NewContext 将 logger 放入 context(中间件使用)
func RegisterAdapter ¶ added in v1.6.0
func RegisterAdapter(name string, factory AdapterFactory)
RegisterAdapter 注册适配器
Example ¶
示例 8:注册自定义适配器
package main
import (
"github.com/go-admin-team/go-admin-core/logger"
)
func main() {
// 注册自定义适配器
logger.RegisterAdapter("custom", func(opts ...logger.Option) logger.Logger {
// 实现自定义 Logger
return logger.NewLogger(opts...)
})
// 使用自定义适配器
cfg := &logger.Config{
Adapter: logger.AdapterConfig{
Type: "custom",
},
}
log, _ := logger.NewFromConfig(cfg)
if ext, ok := log.(interface {
Info(msg string, fields ...logger.Field)
}); ok {
ext.Info("Using custom adapter")
}
}
Types ¶
type AdapterConfig ¶ added in v1.6.0
type AdapterConfig struct {
// Type 适配器类型: zap, zerolog, logrus, slog, default
Type string `json:"type" yaml:"type"`
// Zap Zap 特定配置
Zap *ZapConfig `json:"zap,omitempty" yaml:"zap,omitempty"`
// Zerolog Zerolog 特定配置
Zerolog *ZerologConfig `json:"zerolog,omitempty" yaml:"zerolog,omitempty"`
// Logrus Logrus 特定配置
Logrus *LogrusConfig `json:"logrus,omitempty" yaml:"logrus,omitempty"`
}
AdapterConfig 适配器配置
type AdapterFactory ¶ added in v1.6.0
AdapterFactory 适配器工厂
func GetAdapter ¶ added in v1.6.0
func GetAdapter(name string) (AdapterFactory, error)
GetAdapter 获取适配器
type AsyncConfig ¶ added in v1.6.1
type AsyncConfig struct {
// BufferSize 缓冲区大小(队列长度)
BufferSize int
// FlushInterval 刷新间隔(定时批量写入)
FlushInterval time.Duration
// OnDropped 队列满时回调(用于监控丢弃的日志)
OnDropped func(level Level, msg string)
// DropPolicy 队列满时策略
// - "drop": 丢弃新日志(默认)
// - "block": 阻塞等待
// - "sample": 降级采样(每10条记录1条)
DropPolicy string
}
AsyncConfig 异步日志配置
type AsyncPluginConfig ¶ added in v1.6.0
type AsyncPluginConfig struct {
// Enabled 是否启用
Enabled bool `json:"enabled" yaml:"enabled"`
// BufferSize 缓冲区大小
BufferSize int `json:"bufferSize" yaml:"bufferSize"`
// FlushInterval 刷新间隔
FlushInterval time.Duration `json:"flushInterval" yaml:"flushInterval"`
// DropOnFull 缓冲区满时丢弃日志(否则阻塞)
DropOnFull bool `json:"dropOnFull" yaml:"dropOnFull"`
}
AsyncPluginConfig 异步写入插件配置
type CallerHook ¶ added in v1.6.1
type CallerHook struct {
// contains filtered or unexported fields
}
CallerHook 修正调用者信息的 Hook(跳过 logger 包装层)
func NewCallerHook ¶ added in v1.6.1
func NewCallerHook(skip int) *CallerHook
func (*CallerHook) Levels ¶ added in v1.6.1
func (h *CallerHook) Levels() []logrus.Level
type Config ¶ added in v1.6.0
type Config struct {
// Core 核心配置
Core CoreConfig `json:"core" yaml:"core"`
// Adapter 适配器配置
Adapter AdapterConfig `json:"adapter" yaml:"adapter"`
// Output 输出配置
Output OutputConfig `json:"output" yaml:"output"`
// Plugins 插件配置
Plugins PluginsConfig `json:"plugins" yaml:"plugins"`
}
Config 日志配置(完整版,支持所有特性)
func FromLegacyConfig ¶ added in v1.6.0
func FromLegacyConfig(legacy *LegacyConfig) *Config
FromLegacyConfig 从旧配置格式转换(兼容性)
Example ¶
示例 7:从旧配置迁移(向后兼容)
package main
import (
"github.com/go-admin-team/go-admin-core/logger"
)
func main() {
legacyCfg := &logger.LegacyConfig{
Path: "temp/logs",
Stdout: "",
Level: "info",
EnabledDB: false,
}
cfg := logger.FromLegacyConfig(legacyCfg)
log, err := logger.NewFromConfig(cfg)
if err != nil {
panic(err)
}
if ext, ok := log.(interface {
Info(msg string, fields ...logger.Field)
}); ok {
ext.Info("Migrated from legacy config")
}
}
type ConsoleConfig ¶ added in v1.6.0
type ConsoleConfig struct {
// Enabled 是否启用
Enabled bool `json:"enabled" yaml:"enabled"`
// Color 是否启用彩色输出
Color bool `json:"color" yaml:"color"`
// Level 控制台日志级别(可与文件不同)
Level string `json:"level" yaml:"level"`
}
ConsoleConfig 控制台输出配置
type ConsoleFormatter ¶ added in v1.6.1
ConsoleFormatter 自定义控制台格式化器 - 简洁优雅(GORM 风格)
type CoreConfig ¶ added in v1.6.0
type CoreConfig struct {
// Level 日志级别: trace, debug, info, warn, error, fatal
Level string `json:"level" yaml:"level"`
// EnableCaller 是否启用调用者信息(文件名:行号)
EnableCaller bool `json:"enableCaller" yaml:"enableCaller"`
// CallerSkip 跳过的调用栈层数
CallerSkip int `json:"callerSkip" yaml:"callerSkip"`
// EnableStacktrace 是否启用堆栈跟踪(Error 级别以上)
EnableStacktrace bool `json:"enableStacktrace" yaml:"enableStacktrace"`
// Name Logger 名称(用于区分不同模块)
Name string `json:"name" yaml:"name"`
// Fields 默认字段(所有日志都会包含)
Fields map[string]interface{} `json:"fields" yaml:"fields"`
}
CoreConfig 核心配置
type ElasticsearchHook ¶ added in v1.6.0
type ElasticsearchHook struct {
// contains filtered or unexported fields
}
ElasticsearchHook Elasticsearch 日志存储 Hook
func NewElasticsearchHook ¶ added in v1.6.0
func NewElasticsearchHook(client interface{}, index string) *ElasticsearchHook
func (*ElasticsearchHook) Fire ¶ added in v1.6.0
func (h *ElasticsearchHook) Fire(entry *logrus.Entry) error
func (*ElasticsearchHook) Levels ¶ added in v1.6.0
func (h *ElasticsearchHook) Levels() []logrus.Level
type Field ¶ added in v1.6.0
type Field struct {
Key string
Type FieldType
Int64 int64 // 存储 int、bool、duration、time
String string // 存储 string
Any interface{} // 存储 error、复杂类型
}
Field 结构化日志字段(零分配)
func FieldError ¶ added in v1.6.0
FieldError 错误字段(避免与 level.Error() 冲突)
func FieldString ¶ added in v1.6.0
FieldString 字符串字段(避免与 logger.String() 冲突)
type FileConfig ¶ added in v1.6.0
type FileConfig struct {
// Enabled 是否启用
Enabled bool `json:"enabled" yaml:"enabled"`
// Path 日志文件路径
Path string `json:"path" yaml:"path"`
// Level 文件日志级别
Level string `json:"level" yaml:"level"`
// MaxSize 单个文件最大大小(MB)
MaxSize int `json:"maxSize" yaml:"maxSize"`
// MaxAge 文件最大保留天数
MaxAge int `json:"maxAge" yaml:"maxAge"`
// MaxBackups 最大备份数量
MaxBackups int `json:"maxBackups" yaml:"maxBackups"`
// Compress 是否压缩旧日志
Compress bool `json:"compress" yaml:"compress"`
// LocalTime 使用本地时间(而非 UTC)
LocalTime bool `json:"localTime" yaml:"localTime"`
}
FileConfig 文件输出配置
type Helper ¶
type Helper struct {
Logger
// contains filtered or unexported fields
}
Helper 日志辅助器(API 层、Service 层、Job 层通用) 提供简洁的日志 API,支持结构化日志和链式调用
使用示例:
e.Log.Infow("用户登录成功",
"user_id", 123,
"ip", "192.168.1.1",
)
e.Log.WithError(err).Error("数据库查询失败")
性能优化:
- 每个方法都先检查日志级别,避免无效调用
- fields 采用 map 存储,支持高效合并
func FromContext ¶
FromContext 从 context 中获取 logger 如果不存在,返回默认 logger(保证永远不返回 nil)
func (*Helper) Infow ¶ added in v1.6.1
Infow 使用结构化字段记录 INFO 日志 性能优化:先检查级别,再构建字段 map 使用示例:e.Log.Infow("用户登录", "user_id", 123, "ip", "192.168.1.1")
func (*Helper) WithFields ¶
type LegacyConfig ¶ added in v1.6.0
type LegacyConfig struct {
Path string `json:"path" yaml:"path"`
Stdout string `json:"stdout" yaml:"stdout"`
Level string `json:"level" yaml:"level"`
EnabledDB bool `json:"enableddb" yaml:"enableddb"`
}
LegacyConfig 旧配置格式(向后兼容)
type Level ¶
type Level int8
const ( // TraceLevel level. Designates finer-grained informational events than the Debug. TraceLevel Level = iota - 2 // DebugLevel level. Usually only enabled when debugging. Very verbose logging. DebugLevel // InfoLevel is the default logging priority. // General operational entries about what's going on inside the application. InfoLevel // WarnLevel level. Non-critical entries that deserve eyes. WarnLevel // ErrorLevel level. Logs. Used for errors that should definitely be noted. ErrorLevel // FatalLevel level. Logs and then calls `logger.Exit(1)`. highest level of severity. FatalLevel )
func GetLevel ¶
GetLevel converts a level string into a logger Level value. returns an error if the input string does not match known values.
type Logger ¶
type Logger interface {
// Init initialises options
Init(options ...Option) error
// Options The Logger options
Options() Options
// Fields set fields to always be logged
Fields(fields map[string]interface{}) Logger
// Log writes a log entry
Log(level Level, v ...interface{})
// Logf writes a formatted log entry
Logf(level Level, format string, v ...interface{})
// String returns the name of logger
String() string
}
Logger is a generic logging interface
var ( // DefaultLogger logger DefaultLogger Logger )
func NewAsyncLogger ¶ added in v1.6.1
func NewAsyncLogger(logger Logger, config AsyncConfig) Logger
NewAsyncLogger 创建异步 logger
func NewDevelopmentLogger ¶ added in v1.6.0
func NewDevelopmentLogger() Logger
NewDevelopmentLogger 创建开发环境 Logger(彩色输出,详细信息)
Example ¶
示例 3:开发环境 Logger
package main
import (
"github.com/go-admin-team/go-admin-core/logger"
)
func main() {
log := logger.NewDevelopmentLogger()
// 使用结构化日志 API
if ext, ok := log.(interface {
Debug(msg string, fields ...logger.Field)
Info(msg string, fields ...logger.Field)
Error(msg string, fields ...logger.Field)
}); ok {
ext.Debug("Debug information")
ext.Info("Application running")
ext.Error("Something went wrong")
}
}
func NewFromConfig ¶ added in v1.6.0
NewFromConfig 从配置创建 Logger
Example ¶
示例 2:从配置创建 Logger
package main
import (
"github.com/go-admin-team/go-admin-core/logger"
)
func main() {
cfg := &logger.Config{
Core: logger.CoreConfig{
Level: "info",
Name: "my-service",
},
Adapter: logger.AdapterConfig{
Type: "logrus",
},
Output: logger.OutputConfig{
Console: &logger.ConsoleConfig{
Enabled: true,
Color: true,
},
File: &logger.FileConfig{
Enabled: true,
Path: "logs/app.log",
MaxSize: 100,
MaxBackups: 7,
Compress: true,
},
},
}
log, err := logger.NewFromConfig(cfg)
if err != nil {
panic(err)
}
// 使用结构化日志 API
if ext, ok := log.(interface {
Info(msg string, fields ...logger.Field)
}); ok {
ext.Info("Logger created from config")
}
}
func NewLogrusLogger ¶ added in v1.6.0
NewLogrusLogger 创建基于 Logrus 的 logger
Example ¶
示例 1:使用默认 Logrus Logger
package main
import (
"github.com/go-admin-team/go-admin-core/logger"
)
func main() {
log := logger.NewLogrusLogger(
logger.WithLevel(logger.InfoLevel),
)
// 使用结构化日志 API
if ext, ok := log.(interface {
Info(msg string, fields ...logger.Field)
Warn(msg string, fields ...logger.Field)
}); ok {
ext.Info("Application started")
ext.Warn("This is a warning")
ext.Info("User logged in",
logger.Int("user_id", 123),
logger.FieldString("action", "login"),
)
}
}
Example (AddHook) ¶
示例 6:添加 Logrus Hook(生态优势)
package main
import (
"github.com/go-admin-team/go-admin-core/logger"
)
func main() {
log := logger.NewLogrusLogger()
// 类型断言获取 Logrus 特定功能
if logrusAdapter, ok := log.(interface {
AddHook(hook interface{})
}); ok {
// 添加 Sentry Hook(错误上报)
// sentryHook := logger.NewSentryHook()
// logrusAdapter.AddHook(sentryHook)
// 添加 Elasticsearch Hook(日志存储)
// esHook := logger.NewElasticsearchHook(esClient, "logs")
// logrusAdapter.AddHook(esHook)
// 添加 Metrics Hook(监控)
metricsHook := logger.NewMetricsHook()
logrusAdapter.AddHook(metricsHook)
}
if ext, ok := log.(interface {
Error(msg string, fields ...logger.Field)
}); ok {
ext.Error("This error will trigger hooks")
}
}
Example (StructuredFields) ¶
示例 5:结构化字段
package main
import (
"time"
"github.com/go-admin-team/go-admin-core/logger"
)
func main() {
log := logger.NewLogrusLogger()
// 使用结构化字段 API(推荐)
if ext, ok := log.(interface {
Info(msg string, fields ...logger.Field)
}); ok {
ext.Info("HTTP Request",
logger.RequestID("req-12345"),
logger.UserID(123),
logger.Method("GET"),
logger.URI("/api/users"),
logger.StatusCode(200),
logger.Latency(100*time.Millisecond),
logger.ClientIP("192.168.1.1"),
)
}
}
func NewProductionLogger ¶ added in v1.6.0
NewProductionLogger 创建生产环境 Logger(JSON 格式,高性能)
Example ¶
示例 4:生产环境 Logger(带采样)
package main
import (
"github.com/go-admin-team/go-admin-core/logger"
)
func main() {
log := logger.NewProductionLogger("logs/production.log")
// 使用结构化日志 API
if ext, ok := log.(interface {
Info(msg string, fields ...logger.Field)
}); ok {
// 高频日志会被采样
for i := 0; i < 1000; i++ {
ext.Info("Processing request")
}
}
// Error 级别不会被采样
if ext, ok := log.(interface {
Error(msg string, fields ...logger.Field)
}); ok {
ext.Error("Critical error occurred")
}
}
func NewSamplingLogger ¶ added in v1.6.0
func NewSamplingLogger(logger Logger, config SamplingConfig) Logger
NewSamplingLogger 创建采样 logger
func NewSanitizerLogger ¶ added in v1.6.1
func NewSanitizerLogger(logger Logger, config SanitizerConfig) Logger
NewSanitizerLogger 创建脱敏 logger
func NewTestLogger ¶ added in v1.6.0
func NewTestLogger() Logger
NewTestLogger 创建测试环境 Logger(内存输出,不写文件)
func NewZapLogger ¶ added in v1.6.0
NewZapLogger 创建基于 zap 的高性能 logger
func SetupLogger ¶ added in v1.6.0
func SetupLogger(cfg interface{}) Logger
SetupLogger 从配置设置全局 Logger(向后兼容)
type LogrusConfig ¶ added in v1.6.0
type LogrusConfig struct {
// Formatter 格式化器: json, text
Formatter string `json:"formatter" yaml:"formatter"`
}
LogrusConfig Logrus 适配器配置
type MetricsHook ¶ added in v1.6.0
type MetricsHook struct {
// contains filtered or unexported fields
}
MetricsHook Prometheus 监控 Hook
func NewMetricsHook ¶ added in v1.6.0
func NewMetricsHook() *MetricsHook
func (*MetricsHook) Levels ¶ added in v1.6.0
func (h *MetricsHook) Levels() []logrus.Level
type MetricsPluginConfig ¶ added in v1.6.0
type MetricsPluginConfig struct {
// Enabled 是否启用
Enabled bool `json:"enabled" yaml:"enabled"`
// Namespace Prometheus Namespace
Namespace string `json:"namespace" yaml:"namespace"`
// Subsystem Prometheus Subsystem
Subsystem string `json:"subsystem" yaml:"subsystem"`
}
MetricsPluginConfig 监控插件配置
type NetworkConfig ¶ added in v1.6.0
type NetworkConfig struct {
// Type 类型: kafka, elasticsearch, fluentd, syslog
Type string `json:"type" yaml:"type"`
// Endpoints 端点列表
Endpoints []string `json:"endpoints" yaml:"endpoints"`
// Topic Kafka Topic
Topic string `json:"topic" yaml:"topic"`
// Index Elasticsearch Index
Index string `json:"index" yaml:"index"`
// BufferSize 缓冲区大小
BufferSize int `json:"bufferSize" yaml:"bufferSize"`
// FlushInterval 刷新间隔
FlushInterval time.Duration `json:"flushInterval" yaml:"flushInterval"`
}
NetworkConfig 网络输出配置
type Option ¶
type Option func(*Options)
Option is a function that configures the logger options Option 是一个配置日志记录器选项的函数
func SetOption ¶
func SetOption(k, v interface{}) Option
SetOption sets a custom option SetOption 设置自定义选项
func WithAsync ¶ added in v1.6.1
func WithAsync(config AsyncConfig) Option
WithAsync sets async configuration for the logger WithAsync 设置异步日志配置
func WithCallerSkipCount ¶
WithCallerSkipCount sets frame count to skip WithCallerSkipCount 设置要跳过的帧数
func WithFields ¶
WithFields sets default fields for the logger WithFields 设置日志记录器的默认字段
func WithOutput ¶
WithOutput sets default output writer for the logger WithOutput 设置日志记录器的默认输出写入器
func WithSampling ¶ added in v1.6.1
func WithSampling(config SamplingConfig) Option
WithSampling sets sampling configuration for the logger WithSampling 设置日志采样配置
func WithSanitizer ¶ added in v1.6.1
func WithSanitizer(config SanitizerConfig) Option
WithSanitizer sets sanitizer configuration for the logger WithSanitizer 设置脱敏配置
func WithStdout ¶ added in v1.6.0
WithStdout sets whether to enable console output WithStdout 设置是否启用控制台输出
type Options ¶
type Options struct {
// Level is the logging level the logger should log at. default is `InfoLevel`
// Level 是日志记录器的日志级别,默认是 `InfoLevel`
Level Level
// Fields are fields to always be logged
// Fields 是始终要记录的字段
Fields map[string]interface{}
// Out is the output writer for the logger. default is `os.Stderr`
// Out 是日志记录器的输出写入器,默认是 `os.Stderr`
Out io.Writer
// CallerSkipCount is the frame count to skip for file:line info
// CallerSkipCount 是跳过的帧数,用于文件:行信息
CallerSkipCount int
// Context is alternative options
// Context 是替代选项
Context context.Context
// Name is the logger name
// Name 是日志记录器的名称
Name string
// Path is the log file path (optional)
// Path 是日志文件路径(可选)
Path string
// Stdout enables console output
// Stdout 启用控制台输出
Stdout bool
// --- 日志轮转配置 ---
// MaxSize 单个文件最大大小(MB),默认 100
MaxSize int
// MaxAge 文件最大保留天数,默认 30
MaxAge int
// MaxBackups 最大备份数量,默认 7
MaxBackups int
// Compress 是否压缩旧日志,默认 true
Compress bool
// LocalTime 使用本地时间(而非 UTC),默认 true
LocalTime bool
}
Options are logger options Options 是日志记录器选项
func DefaultOptions ¶ added in v1.6.0
func DefaultOptions() Options
DefaultOptions returns default options DefaultOptions 返回默认选项
type OutputConfig ¶ added in v1.6.0
type OutputConfig struct {
// Console 控制台输出配置
Console *ConsoleConfig `json:"console,omitempty" yaml:"console,omitempty"`
// File 文件输出配置
File *FileConfig `json:"file,omitempty" yaml:"file,omitempty"`
// Network 网络输出配置(Kafka、Elasticsearch 等)
Network *NetworkConfig `json:"network,omitempty" yaml:"network,omitempty"`
// Format 输出格式: json, text, console
Format string `json:"format" yaml:"format"`
// Encoding 编码格式: json, console, text
Encoding string `json:"encoding" yaml:"encoding"`
}
OutputConfig 输出配置
type PluginsConfig ¶ added in v1.6.0
type PluginsConfig struct {
// Sampling 采样配置
Sampling *SamplingPluginConfig `json:"sampling,omitempty" yaml:"sampling,omitempty"`
// Metrics 监控配置
Metrics *MetricsPluginConfig `json:"metrics,omitempty" yaml:"metrics,omitempty"`
// Tracing 链路追踪配置
Tracing *TracingPluginConfig `json:"tracing,omitempty" yaml:"tracing,omitempty"`
// Sanitize 脱敏配置
Sanitize *SanitizePluginConfig `json:"sanitize,omitempty" yaml:"sanitize,omitempty"`
// Async 异步写入配置
Async *AsyncPluginConfig `json:"async,omitempty" yaml:"async,omitempty"`
}
PluginsConfig 插件配置
type SamplingConfig ¶ added in v1.6.0
type SamplingConfig struct {
// Initial 每个 Tick 周期内前 N 条日志必须记录
Initial int
// Thereafter 超过 Initial 后,每 M 条记录 1 条
Thereafter int
// Tick 采样周期(例如:每秒、每分钟重置计数器)
Tick time.Duration
}
SamplingConfig 采样配置
type SamplingPluginConfig ¶ added in v1.6.0
type SamplingPluginConfig struct {
// Enabled 是否启用
Enabled bool `json:"enabled" yaml:"enabled"`
// Initial 每个周期前 N 条必记录
Initial int `json:"initial" yaml:"initial"`
// Thereafter 之后每 M 条记录 1 条
Thereafter int `json:"thereafter" yaml:"thereafter"`
// Tick 采样周期
Tick time.Duration `json:"tick" yaml:"tick"`
// ExcludeLevels 排除的日志级别(Error 级别不采样)
ExcludeLevels []string `json:"excludeLevels" yaml:"excludeLevels"`
}
SamplingPluginConfig 采样插件配置
type SanitizePluginConfig ¶ added in v1.6.0
type SanitizePluginConfig struct {
// Enabled 是否启用
Enabled bool `json:"enabled" yaml:"enabled"`
// Rules 脱敏规则
Rules []SanitizeRule `json:"rules" yaml:"rules"`
}
SanitizePluginConfig 脱敏插件配置
type SanitizeRule ¶ added in v1.6.0
type SanitizeRule struct {
// FieldPattern 字段名正则(如 password|token|secret)
FieldPattern string `json:"fieldPattern" yaml:"fieldPattern"`
// Strategy 脱敏策略: mask_all, mask_partial, hash
Strategy string `json:"strategy" yaml:"strategy"`
// MaskChar 掩码字符
MaskChar string `json:"maskChar" yaml:"maskChar"`
}
SanitizeRule 脱敏规则
type SanitizerConfig ¶ added in v1.6.1
type SanitizerConfig struct {
// Enabled 是否启用脱敏
Enabled bool
// Rules 脱敏规则列表
Rules []SanitizerRule
// CustomMatcher 自定义字段匹配函数(可选)
CustomMatcher func(fieldName string) *SanitizerRule
}
SanitizerConfig 脱敏配置
type SanitizerRule ¶ added in v1.6.1
type SanitizerRule struct {
// FieldPattern 字段名匹配(精确匹配或后缀匹配)
// 例如:"phone", "idcard", "*_token"(*表示后缀匹配)
FieldPattern string
// Strategy 脱敏策略
// - "mask": 掩码(保留前后,中间替换为 *)
// - "hash": SHA256 哈希
// - "remove": 完全删除字段
Strategy string
// MaskChar 掩码字符(默认 "*")
MaskChar string
// KeepPrefix 保留前缀长度(mask 策略)
KeepPrefix int
// KeepSuffix 保留后缀长度(mask 策略)
KeepSuffix int
}
SanitizerRule 脱敏规则
type SentryHook ¶ added in v1.6.0
type SentryHook struct {
// contains filtered or unexported fields
}
SentryHook Sentry 错误上报 Hook
func NewSentryHook ¶ added in v1.6.0
func NewSentryHook() *SentryHook
func (*SentryHook) Levels ¶ added in v1.6.0
func (h *SentryHook) Levels() []logrus.Level
type TracingPluginConfig ¶ added in v1.6.0
type TracingPluginConfig struct {
// Enabled 是否启用
Enabled bool `json:"enabled" yaml:"enabled"`
// Provider 追踪提供商: opentelemetry, jaeger, zipkin
Provider string `json:"provider" yaml:"provider"`
// AutoExtract 自动从 context 提取 trace_id/span_id
AutoExtract bool `json:"autoExtract" yaml:"autoExtract"`
}
TracingPluginConfig 链路追踪插件配置
type ZapConfig ¶ added in v1.6.0
type ZapConfig struct {
// Development 开发模式(更友好的输出格式)
Development bool `json:"development" yaml:"development"`
// DisableCaller 禁用调用者信息
DisableCaller bool `json:"disableCaller" yaml:"disableCaller"`
// DisableStacktrace 禁用堆栈跟踪
DisableStacktrace bool `json:"disableStacktrace" yaml:"disableStacktrace"`
// Sampling 采样配置(Zap 内置)
Sampling *ZapSamplingConfig `json:"sampling,omitempty" yaml:"sampling,omitempty"`
}
ZapConfig Zap 适配器配置
type ZapSamplingConfig ¶ added in v1.6.0
type ZapSamplingConfig struct {
Initial int `json:"initial" yaml:"initial"`
Thereafter int `json:"thereafter" yaml:"thereafter"`
}
ZapSamplingConfig Zap 采样配置
type ZerologConfig ¶ added in v1.6.0
type ZerologConfig struct {
// TimeFormat 时间格式: unix, unixms, rfc3339
TimeFormat string `json:"timeFormat" yaml:"timeFormat"`
}
ZerologConfig Zerolog 适配器配置