logger

package
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2026 License: Apache-2.0 Imports: 20 Imported by: 173

Documentation

Index

Examples

Constants

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

View Source
var DefaultAsyncConfig = AsyncConfig{
	BufferSize:    10000,
	FlushInterval: 100 * time.Millisecond,
	DropPolicy:    "drop",
	OnDropped:     nil,
}

DefaultAsyncConfig 默认异步配置(生产环境推荐)

View Source
var DefaultSamplingConfig = SamplingConfig{
	Initial:    10,
	Thereafter: 100,
	Tick:       time.Second,
}

DefaultSamplingConfig 默认采样配置(生产环境推荐)

View Source
var DefaultSanitizerConfig = SanitizerConfig{
	Enabled: true,
	Rules:   DefaultSanitizerRules,
}

DefaultSanitizerConfig 默认脱敏配置

View Source
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 Debug

func Debug(args ...interface{})

func Debugf

func Debugf(template string, args ...interface{})

func Error

func Error(args ...interface{})

func Errorf

func Errorf(template string, args ...interface{})

func Fatal

func Fatal(args ...interface{})

func Fatalf

func Fatalf(template string, args ...interface{})

func Info

func Info(args ...interface{})

Info logs a message at the info log level.

func Infof

func Infof(template string, args ...interface{})

func Init

func Init(opts ...Option) error

func ListAdapters added in v1.6.0

func ListAdapters() []string

ListAdapters 列出所有已注册的适配器

func Log

func Log(level Level, v ...interface{})

func Logf

func Logf(level Level, format string, v ...interface{})

func NewContext

func NewContext(ctx context.Context, l *Helper) context.Context

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")
	}
}

func String

func String() string

func Trace

func Trace(args ...interface{})

func Tracef

func Tracef(template string, args ...interface{})

func V

func V(lvl Level, log Logger) bool

Returns true if the given level is at or lower the current logger level

func Warn

func Warn(args ...interface{})

func Warnf

func Warnf(template string, args ...interface{})

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

type AdapterFactory func(opts ...Option) Logger

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) Fire added in v1.6.1

func (h *CallerHook) Fire(entry *logrus.Entry) error

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 DefaultConfig added in v1.6.0

func DefaultConfig() *Config

DefaultConfig 默认配置

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")
	}
}

func (*Config) Validate added in v1.6.0

func (c *Config) Validate() error

Validate 验证配置

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

type ConsoleFormatter struct {
	TimestampFormat string
	ForceColors     bool
}

ConsoleFormatter 自定义控制台格式化器 - 简洁优雅(GORM 风格)

func (*ConsoleFormatter) Format added in v1.6.1

func (f *ConsoleFormatter) Format(entry *logrus.Entry) ([]byte, error)

Format 实现 logrus.Formatter 接口(GORM 风格) 性能优化:复用 entry.Buffer,避免频繁分配内存

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 Any added in v1.6.0

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

Any 任意类型字段(性能较低,尽量少用)

func Bool added in v1.6.0

func Bool(key string, val bool) Field

Bool 布尔字段

func ClientIP added in v1.6.0

func ClientIP(val string) Field

ClientIP 客户端 IP 字段

func Duration added in v1.6.0

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

Duration 时长字段

func FieldError added in v1.6.0

func FieldError(err error) Field

FieldError 错误字段(避免与 level.Error() 冲突)

func FieldString added in v1.6.0

func FieldString(key string, val string) Field

FieldString 字符串字段(避免与 logger.String() 冲突)

func Int added in v1.6.0

func Int(key string, val int) Field

Int 整数字段

func Int64 added in v1.6.0

func Int64(key string, val int64) Field

Int64 64位整数字段

func Latency added in v1.6.0

func Latency(val time.Duration) Field

Latency 请求延迟字段

func Method added in v1.6.0

func Method(val string) Field

Method HTTP 方法字段

func RequestID added in v1.6.0

func RequestID(val string) Field

RequestID 请求 ID 字段

func StatusCode added in v1.6.0

func StatusCode(val int) Field

StatusCode HTTP 状态码字段

func Time added in v1.6.0

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

Time 时间字段

func TraceID added in v1.6.0

func TraceID(val string) Field

TraceID 链路追踪 ID 字段

func URI added in v1.6.0

func URI(val string) Field

URI 请求路径字段

func UserID added in v1.6.0

func UserID(val int64) Field

UserID 用户 ID 字段

type FieldType added in v1.6.0

type FieldType uint8

FieldType 字段类型(零分配设计)

const (
	FieldTypeAny FieldType = iota
	FieldTypeString
	FieldTypeInt
	FieldTypeBool
	FieldTypeDuration
	FieldTypeTime
	FieldTypeError
)

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

func FromContext(ctx context.Context) *Helper

FromContext 从 context 中获取 logger 如果不存在,返回默认 logger(保证永远不返回 nil)

func NewHelper

func NewHelper(log Logger) *Helper

func (*Helper) Debug

func (h *Helper) Debug(args ...interface{})

func (*Helper) Debugf

func (h *Helper) Debugf(template string, args ...interface{})

func (*Helper) Debugw added in v1.6.1

func (h *Helper) Debugw(msg string, keysAndValues ...interface{})

Debugw 使用结构化字段记录 DEBUG 日志

func (*Helper) Error

func (h *Helper) Error(args ...interface{})

func (*Helper) Errorf

func (h *Helper) Errorf(template string, args ...interface{})

func (*Helper) Errorw added in v1.6.1

func (h *Helper) Errorw(msg string, keysAndValues ...interface{})

Errorw 使用结构化字段记录 ERROR 日志

func (*Helper) Fatal

func (h *Helper) Fatal(args ...interface{})

func (*Helper) Fatalf

func (h *Helper) Fatalf(template string, args ...interface{})

func (*Helper) Info

func (h *Helper) Info(args ...interface{})

func (*Helper) Infof

func (h *Helper) Infof(template string, args ...interface{})

func (*Helper) Infow added in v1.6.1

func (h *Helper) Infow(msg string, keysAndValues ...interface{})

Infow 使用结构化字段记录 INFO 日志 性能优化:先检查级别,再构建字段 map 使用示例:e.Log.Infow("用户登录", "user_id", 123, "ip", "192.168.1.1")

func (*Helper) Trace

func (h *Helper) Trace(args ...interface{})

func (*Helper) Tracef

func (h *Helper) Tracef(template string, args ...interface{})

func (*Helper) Warn

func (h *Helper) Warn(args ...interface{})

func (*Helper) Warnf

func (h *Helper) Warnf(template string, args ...interface{})

func (*Helper) Warnw added in v1.6.1

func (h *Helper) Warnw(msg string, keysAndValues ...interface{})

Warnw 使用结构化字段记录 WARN 日志

func (*Helper) WithError

func (h *Helper) WithError(err error) *Helper

func (*Helper) WithFields

func (h *Helper) WithFields(fields map[string]interface{}) *Helper

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

func GetLevel(levelStr string) (Level, error)

GetLevel converts a level string into a logger Level value. returns an error if the input string does not match known values.

func (Level) Enabled

func (l Level) Enabled(lvl Level) bool

Enabled returns true if the given level is at or above this level.

func (Level) LevelForGorm

func (l Level) LevelForGorm() int

LevelForGorm 转换成gorm日志级别

func (Level) String

func (l Level) String() string

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 Fields

func Fields(fields map[string]interface{}) 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

func NewFromConfig(cfg *Config) (Logger, error)

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 NewLogger

func NewLogger(opts ...Option) Logger

NewLogger 创建一个新的日志记录器 NewLogger creates a new logger

func NewLogrusLogger added in v1.6.0

func NewLogrusLogger(opts ...Option) Logger

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

func NewProductionLogger(logPath string) Logger

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

func NewZapLogger(opts ...Option) Logger

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) Fire added in v1.6.0

func (h *MetricsHook) Fire(entry *logrus.Entry) error

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

func WithCallerSkipCount(c int) Option

WithCallerSkipCount sets frame count to skip WithCallerSkipCount 设置要跳过的帧数

func WithFields

func WithFields(fields map[string]interface{}) Option

WithFields sets default fields for the logger WithFields 设置日志记录器的默认字段

func WithLevel

func WithLevel(level Level) Option

WithLevel sets default level for the logger WithLevel 设置日志记录器的默认级别

func WithName added in v1.2.3

func WithName(name string) Option

WithName sets name for logger WithName 设置日志记录器的名称

func WithOutput

func WithOutput(out io.Writer) Option

WithOutput sets default output writer for the logger WithOutput 设置日志记录器的默认输出写入器

func WithPath added in v1.6.0

func WithPath(path string) Option

WithPath sets the log file path WithPath 设置日志文件路径

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

func WithStdout(enabled bool) Option

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) Fire added in v1.6.0

func (h *SentryHook) Fire(entry *logrus.Entry) error

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 适配器配置

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL