logging

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 12 Imported by: 0

README

Logging Package

基于 zaplumberjack 的高性能结构化日志系统。

特性

  • 高性能: 基于 Uber 的 zap 日志库,零分配设计
  • 日志轮转: 使用 lumberjack 实现自动日志轮转(按大小、时间、数量)
  • 按级别分文件: 不同日志级别输出到不同文件(debug.log, info.log, error.log 等)
  • 按日期分目录: 日志文件按日期自动归档到子目录
  • 多输出: 支持同时输出到终端和文件
  • 结构化日志: 支持 JSON 和 Console 两种输出格式
  • 上下文感知: 自动从 context 提取 trace_id、span_id、request_id 等
  • HTTP 中间件: 内置请求日志和 panic 恢复中间件
  • Hook 系统: 支持自定义日志处理钩子
  • 工厂模式: 支持创建命名的子日志器

快速开始

基本使用
package main

import (
    "github.com/leeforge/framework/logging"
    "go.uber.org/zap"
)

func main() {
    // 使用默认配置初始化全局日志器
    logging.Init(logging.DefaultConfig())
    defer logging.Sync()

    // 包级别函数 - 使用全局日志器
    logging.Info("应用启动", zap.String("version", "1.0.0"))
    logging.Debug("调试信息")
    logging.Warn("警告信息")
    logging.Error("错误信息", zap.Error(err))

    // 格式化日志
    logging.Infof("用户 %s 登录成功", username)
    logging.Errorf("请求失败: %v", err)
}
自定义配置
config := logging.Config{
    Director:       "logs",           // 日志目录
    Level:          "debug",          // 最低日志级别
    Format:         "json",           // 输出格式: json 或 console
    LogInTerminal:  true,             // 是否同时输出到终端
    MaxSize:        100,              // 单文件最大大小 (MB)
    MaxBackups:     10,               // 保留的旧文件数量
    MaxAge:         7,                // 保留天数
    Compress:       true,             // 是否压缩旧文件
    ShowLineNumber: true,             // 是否显示调用位置
    TimeFormat:     "2006/01/02 - 15:04:05",
    EncodeLevel:    "LowercaseLevelEncoder", // 级别编码器
}

logging.Init(config)
创建独立日志器
// 创建独立的日志器实例
logger := logging.NewLogger(config)
logger.Info("独立日志器")

// 创建子日志器
childLogger := logger.With(zap.String("module", "user"))
childLogger.Info("用户模块日志")

// 命名日志器
namedLogger := logger.Named("auth")
namedLogger.Info("认证模块日志")

// 错误日志器
errLogger := logger.WithError(err)
errLogger.Error("操作失败")

配置项说明

字段 类型 默认值 说明
Director string "logs" 日志文件存储目录
Level string "info" 最低日志级别 (debug/info/warn/error/dpanic/panic/fatal)
Format string "json" 输出格式 (json/console)
LogInTerminal bool true 是否同时输出到终端
MaxSize int 100 单个日志文件最大大小 (MB)
MaxBackups int 10 保留的旧日志文件数量
MaxAge int 7 日志文件保留天数
Compress bool true 是否压缩归档的日志文件
ShowLineNumber bool true 是否在日志中显示调用位置
TimeFormat string "2006/01/02 - 15:04:05" 时间格式
Prefix string "" 日志前缀
EncodeLevel string "LowercaseLevelEncoder" 级别编码器
EncodeLevel 可选值
  • LowercaseLevelEncoder - 小写 (info, error)
  • LowercaseColorLevelEncoder - 小写带颜色
  • CapitalLevelEncoder - 大写 (INFO, ERROR)
  • CapitalColorLevelEncoder - 大写带颜色

日志文件结构

logs/
├── 2026-01-20/
│   ├── debug.log
│   ├── info.log
│   ├── warn.log
│   ├── error.log
│   └── fatal.log
├── 2026-01-21/
│   ├── debug.log
│   ├── info.log
│   └── ...

上下文日志

设置上下文信息
ctx := context.Background()
ctx = logging.SetTraceID(ctx, "trace-123")
ctx = logging.SetSpanID(ctx, "span-456")
ctx = logging.SetRequestID(ctx, "req-789")
ctx = logging.SetUserID(ctx, "user-abc")
从上下文创建日志器
// 自动提取 context 中的 trace_id, span_id 等字段
ctxLogger := logging.WithContext(logger, ctx)
ctxLogger.Info("带上下文的日志")
// 输出: {"message":"带上下文的日志","trace_id":"trace-123","span_id":"span-456",...}
在上下文中存储/获取日志器
// 存储日志器到 context
ctx = logging.ToContext(ctx, logger)

// 从 context 获取日志器 (如果没有则返回全局日志器)
logger := logging.FromContext(ctx)

HTTP 中间件

请求日志中间件
import (
    "net/http"
    "github.com/go-chi/chi/v5"
    "github.com/leeforge/framework/logging"
)

func main() {
    logger := logging.NewLogger(config)

    r := chi.NewRouter()

    // 添加请求日志中间件
    r.Use(logging.HTTPMiddleware(logger))

    // 添加 panic 恢复中间件
    r.Use(logging.RecoveryMiddleware(logger))

    r.Get("/api/users", handleUsers)
    http.ListenAndServe(":8080", r)
}

中间件会自动记录:

  • 请求开始:method, path, query, remote_addr, user_agent
  • 请求完成:method, path, status, duration, bytes
在 Handler 中使用日志器
func handleUsers(w http.ResponseWriter, r *http.Request) {
    // 从 context 获取日志器 (已包含请求上下文信息)
    logger := logging.FromContext(r.Context())

    logger.Info("处理用户请求", zap.Int("user_count", len(users)))
}

工厂模式

用于管理多个命名的日志器实例:

// 创建工厂
factory := logging.NewFactory(config)

// 获取命名日志器 (相同名称返回相同实例)
userLogger := factory.GetLogger("user-service")
orderLogger := factory.GetLogger("order-service")

userLogger.Info("用户服务日志")
orderLogger.Info("订单服务日志")

Hook 系统

添加自定义日志处理钩子:

import "go.uber.org/zap/zapcore"

// 定义 hook
alertHook := func(entry zapcore.Entry) error {
    if entry.Level >= zapcore.ErrorLevel {
        // 发送告警通知
        sendAlert(entry.Message)
    }
    return nil
}

// 添加单个 hook
hookedLogger := logging.WithHook(logger, alertHook)

// 添加多个 hooks
hookedLogger := logging.WithHooks(logger, alertHook, metricsHook)

访问底层 zap 日志器

logger := logging.NewLogger(config)

// 获取底层 *zap.Logger
zapLogger := logger.Zap()

// 获取底层 *zap.SugaredLogger
sugarLogger := logger.Sugar()

// 使用 zap 的高级特性
zapLogger.With(zap.Namespace("request")).Info("namespaced log")

全局日志器

// 初始化全局日志器
logging.Init(config)

// 获取全局日志器
logger := logging.Global()

// 替换全局日志器
logging.SetGlobal(newLogger)

// 包级别函数直接使用全局日志器
logging.Info("message")
logging.Debug("debug")
logging.Error("error")
logging.Infof("formatted %s", "message")
logging.Debugf("debug %d", 123)

// 刷新缓冲
logging.Sync()

清理资源

// 应用退出时刷新日志缓冲
defer logging.Sync()

// 关闭所有文件写入器 (可选)
defer logging.CloseAllWriters()

日志输出示例

JSON 格式
{"level":"info","time":"2026/01/20 - 15:04:05","caller":"main.go:42","message":"用户登录","user_id":"123","ip":"192.168.1.1"}
{"level":"error","time":"2026/01/20 - 15:04:06","caller":"auth.go:89","message":"认证失败","error":"invalid token","trace_id":"abc-123"}
Console 格式
2026/01/20 - 15:04:05	info	main.go:42	用户登录	{"user_id": "123", "ip": "192.168.1.1"}
2026/01/20 - 15:04:06	error	auth.go:89	认证失败	{"error": "invalid token", "trace_id": "abc-123"}

YAML 配置示例

log:
  director: logs
  level: info
  format: json
  log-in-terminal: true
  max-size: 100
  max-backups: 10
  max-age: 7
  compress: true
  show-line-number: true
  time-format: "2006/01/02 - 15:04:05"
  encode-level: LowercaseLevelEncoder

最佳实践

  1. 初始化: 在应用启动时调用 logging.Init(config) 初始化全局日志器
  2. 清理: 使用 defer logging.Sync() 确保退出时刷新日志缓冲
  3. 上下文: 在 HTTP 处理中使用 FromContext 获取带请求信息的日志器
  4. 命名: 为不同模块创建命名日志器便于区分和过滤
  5. 级别: 生产环境使用 info 级别,开发环境使用 debug 级别
  6. 格式: 生产环境使用 json 格式便于日志分析工具解析

Documentation

Index

Constants

View Source
const (
	// TraceIDKey is the context key for trace ID.
	TraceIDKey ctxKey = "trace_id"
	// SpanIDKey is the context key for span ID.
	SpanIDKey ctxKey = "span_id"
	// RequestIDKey is the context key for request ID.
	RequestIDKey ctxKey = "request_id"
	// UserIDKey is the context key for user ID.
	UserIDKey ctxKey = "user_id"
)

Variables

This section is empty.

Functions

func CloseAllWriters

func CloseAllWriters() error

CloseAllWriters closes all registered writers.

func Colorize

func Colorize(color Color, text string) string

Colorize wraps text with the given color and reset code.

func Colorizef

func Colorizef(color Color, format string, args ...any) string

Colorizef wraps formatted text with the given color.

func CusTimeEncoder

func CusTimeEncoder(config Config) zapcore.TimeEncoder

CusTimeEncoder creates a custom time encoder that adds the prefix and formats the time.

func Debug

func Debug(msg string, fields ...zap.Field)

Debug logs a message at DebugLevel using the global logger.

func Debugf

func Debugf(format string, args ...any)

Debugf logs a formatted message at DebugLevel using the global logger.

func Error

func Error(msg string, fields ...zap.Field)

Error logs a message at ErrorLevel using the global logger.

func Errorf

func Errorf(format string, args ...any)

Errorf logs a formatted message at ErrorLevel using the global logger.

func Fatal

func Fatal(msg string, fields ...zap.Field)

Fatal logs a message at FatalLevel using the global logger and exits.

func Fatalf

func Fatalf(format string, args ...any)

Fatalf logs a formatted message at FatalLevel using the global logger and exits.

func GetEncoder

func GetEncoder(config Config) zapcore.Encoder

GetEncoder returns a zapcore.Encoder based on the config format.

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID extracts request ID from context.

func GetSpanID

func GetSpanID(ctx context.Context) string

GetSpanID extracts span ID from context.

func GetTraceID

func GetTraceID(ctx context.Context) string

GetTraceID extracts trace ID from context.

func GetUserID

func GetUserID(ctx context.Context) string

GetUserID extracts user ID from context.

func HTTPMiddleware

func HTTPMiddleware(logger Logger) func(http.Handler) http.Handler

HTTPMiddleware returns an HTTP middleware that logs requests.

func Info

func Info(msg string, fields ...zap.Field)

Info logs a message at InfoLevel using the global logger.

func Infof

func Infof(format string, args ...any)

Infof logs a formatted message at InfoLevel using the global logger.

func Init

func Init(config Config)

Init initializes the global logger with the given config.

func Pad

func Pad(color Color, text string, width int) string

Pad returns text padded to specified width with color applied.

func PadLeft

func PadLeft(color Color, text string, width int) string

PadLeft returns text left-padded to specified width with color applied.

func RecoveryMiddleware

func RecoveryMiddleware(logger Logger) func(http.Handler) http.Handler

RecoveryMiddleware returns an HTTP middleware that recovers from panics and logs them.

func SetGlobal

func SetGlobal(logger Logger)

SetGlobal replaces the global logger with the given logger.

func SetRequestID

func SetRequestID(ctx context.Context, requestID string) context.Context

SetRequestID adds request ID to context.

func SetSpanID

func SetSpanID(ctx context.Context, spanID string) context.Context

SetSpanID adds span ID to context.

func SetTraceID

func SetTraceID(ctx context.Context, traceID string) context.Context

SetTraceID adds trace ID to context.

func SetUserID

func SetUserID(ctx context.Context, userID string) context.Context

SetUserID adds user ID to context.

func Styled

func Styled(text string, colors ...Color) string

Styled applies combined colors to text and resets. Example: Styled("ERROR", BoldWhite, BgRed) -> bold white "ERROR" on red background.

func Styledf

func Styledf(format string, colors []Color, args ...any) string

Styledf applies combined colors to formatted text and resets.

func Sync

func Sync() error

Sync flushes any buffered log entries from the global logger.

func ToContext

func ToContext(ctx context.Context, logger Logger) context.Context

ToContext stores the Logger in the context.

func Warn

func Warn(msg string, fields ...zap.Field)

Warn logs a message at WarnLevel using the global logger.

func Warnf

func Warnf(format string, args ...any)

Warnf logs a formatted message at WarnLevel using the global logger.

Types

type Color

type Color = string

Color represents a terminal ANSI color escape code.

const (
	Black   Color = "\033[30m"
	Red     Color = "\033[31m"
	Green   Color = "\033[32m"
	Yellow  Color = "\033[33m"
	Blue    Color = "\033[34m"
	Purple  Color = "\033[35m"
	Cyan    Color = "\033[36m"
	White   Color = "\033[37m"
	Gray    Color = "\033[90m"
	Default Color = "\033[39m"
)

Foreground colors

const (
	BoldBlack   Color = "\033[1;30m"
	BoldRed     Color = "\033[1;31m"
	BoldGreen   Color = "\033[1;32m"
	BoldYellow  Color = "\033[1;33m"
	BoldBlue    Color = "\033[1;34m"
	BoldPurple  Color = "\033[1;35m"
	BoldCyan    Color = "\033[1;36m"
	BoldWhite   Color = "\033[1;37m"
	BoldGray    Color = "\033[1;90m"
	BoldDefault Color = "\033[1;39m"
)

Bold foreground colors

const (
	BgBlack   Color = "\033[40m"
	BgRed     Color = "\033[41m"
	BgGreen   Color = "\033[42m"
	BgYellow  Color = "\033[43m"
	BgBlue    Color = "\033[44m"
	BgPurple  Color = "\033[45m"
	BgCyan    Color = "\033[46m"
	BgWhite   Color = "\033[47m"
	BgGray    Color = "\033[100m"
	BgDefault Color = "\033[49m"
)

Background colors

const (
	BgBrightBlack  Color = "\033[100m"
	BgBrightRed    Color = "\033[101m"
	BgBrightGreen  Color = "\033[102m"
	BgBrightYellow Color = "\033[103m"
	BgBrightBlue   Color = "\033[104m"
	BgBrightPurple Color = "\033[105m"
	BgBrightCyan   Color = "\033[106m"
	BgBrightWhite  Color = "\033[107m"
)

Bright background colors (high intensity)

const (
	Bold      Color = "\033[1m"
	Dim       Color = "\033[2m"
	Italic    Color = "\033[3m"
	Underline Color = "\033[4m"
	Blink     Color = "\033[5m"
	Reverse   Color = "\033[7m"
	Hidden    Color = "\033[8m"
	Strike    Color = "\033[9m"
)

Text styles

const (
	Reset Color = "\033[0m"
)

Reset code

func Combine

func Combine(colors ...Color) Color

Combine combines multiple colors/styles into one. Example: Combine(BoldWhite, BgRed) for bold white text on red background.

type ColorScheme

type ColorScheme interface {
	// StatusColor returns the color for an HTTP status code.
	StatusColor(code int) Color
	// MethodColor returns the color for an HTTP method.
	MethodColor(method string) Color
	// DurationColor returns the color based on request duration.
	DurationColor(d time.Duration) Color
	// LevelColor returns the color for a log level.
	LevelColor(level string) Color
}

ColorScheme maps semantic elements to colors. Implement this interface to fully customize color behavior.

type Config

type Config struct {
	// Director is the directory where log files will be stored.
	Director string `mapstructure:"director" json:"director" yaml:"director" toml:"director"`

	// MessageKey is the JSON key for the message field.
	MessageKey string `mapstructure:"message-key" json:"messageKey" yaml:"message-key" toml:"message-key"`

	// LevelKey is the JSON key for the level field.
	LevelKey string `mapstructure:"level-key" json:"levelKey" yaml:"level-key" toml:"level-key"`

	// TimeKey is the JSON key for the timestamp field.
	TimeKey string `mapstructure:"time-key" json:"timeKey" yaml:"time-key" toml:"time-key"`

	// NameKey is the JSON key for the logger name field.
	NameKey string `mapstructure:"name-key" json:"nameKey" yaml:"name-key" toml:"name-key"`

	// CallerKey is the JSON key for the caller field.
	CallerKey string `mapstructure:"caller-key" json:"callerKey" yaml:"caller-key" toml:"caller-key"`

	// LineEnding is the line ending character(s).
	LineEnding string `mapstructure:"line-ending" json:"lineEnding" yaml:"line-ending" toml:"line-ending"`

	// StacktraceKey is the JSON key for the stacktrace field.
	StacktraceKey string `mapstructure:"stacktrace-key" json:"stacktraceKey" yaml:"stacktrace-key" toml:"stacktrace-key"`

	// Level is the minimum log level (debug, info, warn, error, dpanic, panic, fatal).
	Level string `mapstructure:"level" json:"level" yaml:"level" toml:"level"`

	// EncodeLevel is the level encoder type (LowercaseLevelEncoder, LowercaseColorLevelEncoder, CapitalLevelEncoder, CapitalColorLevelEncoder).
	EncodeLevel string `mapstructure:"encode-level" json:"encodeLevel" yaml:"encode-level" toml:"encode-level"`

	// Prefix is the prefix to prepend to each log line.
	Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix" toml:"prefix"`

	// TimeFormat is the time format string (uses Go time format).
	TimeFormat string `mapstructure:"time-format" json:"timeFormat" yaml:"time-format" toml:"time-format"`

	// Format is the log format (json or console).
	Format string `mapstructure:"format" json:"format" yaml:"format" toml:"format"`

	// LogInTerminal enables logging to terminal in addition to file.
	LogInTerminal bool `mapstructure:"log-in-terminal" json:"logInTerminal" yaml:"log-in-terminal" toml:"log-in-terminal"`

	// MaxAge is the maximum number of days to retain old log files.
	MaxAge int `mapstructure:"max-age" json:"maxAge" yaml:"max-age" toml:"max-age"`

	// MaxSize is the maximum size in megabytes of the log file before it gets rotated.
	MaxSize int `mapstructure:"max-size" json:"maxSize" yaml:"max-size" toml:"max-size"`

	// MaxBackups is the maximum number of old log files to retain.
	MaxBackups int `mapstructure:"max-backups" json:"maxBackups" yaml:"max-backups" toml:"max-backups"`

	// Compress determines if the rotated log files should be compressed using gzip.
	Compress bool `mapstructure:"compress" json:"compress" yaml:"compress" toml:"compress"`

	// ShowLineNumber enables adding caller information to log entries.
	ShowLineNumber bool `mapstructure:"show-line-number" json:"showLineNumber" yaml:"show-line-number" toml:"show-line-number"`
}

Config represents the logger configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible defaults.

func (Config) TransportLevel

func (c Config) TransportLevel() zapcore.Level

TransportLevel converts the string level to zapcore.Level.

func (Config) ZapEncodeLevel

func (c Config) ZapEncodeLevel() zapcore.LevelEncoder

ZapEncodeLevel returns the zapcore.LevelEncoder based on EncodeLevel.

type DefaultColorScheme

type DefaultColorScheme struct {
	// Status code colors (foreground + optional background)
	Status1xx Color // Informational
	Status2xx Color // Success
	Status3xx Color // Redirection
	Status4xx Color // Client Error
	Status5xx Color // Server Error

	// HTTP method colors
	MethodGET     Color
	MethodPOST    Color
	MethodPUT     Color
	MethodDELETE  Color
	MethodPATCH   Color
	MethodHEAD    Color
	MethodOPTIONS Color

	// Duration thresholds and colors
	DurationFast          Color         // < FastThreshold
	DurationMedium        Color         // FastThreshold <= d < SlowThreshold
	DurationSlow          Color         // >= SlowThreshold
	DurationFastThreshold time.Duration // Default: 100ms
	DurationSlowThreshold time.Duration // Default: 500ms

	// Log level colors
	LevelDebug Color
	LevelInfo  Color
	LevelWarn  Color
	LevelError Color
	LevelFatal Color
}

DefaultColorScheme provides configurable color mappings with sensible defaults. Override individual fields to customize specific colors. Zero values fall back to sensible defaults.

func NewBackgroundColorScheme

func NewBackgroundColorScheme() *DefaultColorScheme

NewBackgroundColorScheme returns a scheme using background colors for emphasis. Great for status codes and log levels that need to stand out.

func NewBoldColorScheme

func NewBoldColorScheme() *DefaultColorScheme

NewBoldColorScheme returns a scheme with bold foreground colors.

func NewDefaultColorScheme

func NewDefaultColorScheme() *DefaultColorScheme

NewDefaultColorScheme returns a scheme with sensible defaults. All colors use foreground only. Customize fields for background colors.

func (*DefaultColorScheme) DurationColor

func (s *DefaultColorScheme) DurationColor(d time.Duration) Color

DurationColor returns the color based on request duration.

func (*DefaultColorScheme) LevelColor

func (s *DefaultColorScheme) LevelColor(level string) Color

LevelColor returns the color for a log level.

func (*DefaultColorScheme) MethodColor

func (s *DefaultColorScheme) MethodColor(method string) Color

MethodColor returns the color for an HTTP method.

func (*DefaultColorScheme) StatusColor

func (s *DefaultColorScheme) StatusColor(code int) Color

StatusColor returns the color for an HTTP status code.

type Factory

type Factory struct {
	// contains filtered or unexported fields
}

Factory creates and manages named loggers.

func NewFactory

func NewFactory(config Config) *Factory

NewFactory creates a new Factory with the given config.

func (*Factory) Config

func (f *Factory) Config() Config

Config returns a copy of the factory's configuration.

func (*Factory) GetLogger

func (f *Factory) GetLogger(name string) Logger

GetLogger returns a named logger, creating it if necessary. Named loggers share the same configuration but have different names for identification in log output.

type Hook

type Hook func(entry zapcore.Entry) error

Hook is a function that is called for each log entry. It can be used for custom log processing, alerting, metrics, etc.

type Logger

type Logger interface {
	// Debug logs a message at DebugLevel.
	Debug(msg string, fields ...zap.Field)
	// Info logs a message at InfoLevel.
	Info(msg string, fields ...zap.Field)
	// Warn logs a message at WarnLevel.
	Warn(msg string, fields ...zap.Field)
	// Error logs a message at ErrorLevel.
	Error(msg string, fields ...zap.Field)
	// Fatal logs a message at FatalLevel and then calls os.Exit(1).
	Fatal(msg string, fields ...zap.Field)

	// Debugf logs a formatted message at DebugLevel.
	Debugf(format string, args ...any)
	// Infof logs a formatted message at InfoLevel.
	Infof(format string, args ...any)
	// Warnf logs a formatted message at WarnLevel.
	Warnf(format string, args ...any)
	// Errorf logs a formatted message at ErrorLevel.
	Errorf(format string, args ...any)
	// Fatalf logs a formatted message at FatalLevel and then calls os.Exit(1).
	Fatalf(format string, args ...any)

	// With creates a child logger with additional fields.
	With(fields ...zap.Field) Logger
	// WithError creates a child logger with an error field.
	WithError(err error) Logger
	// Named creates a child logger with the given name.
	Named(name string) Logger

	// Zap returns the underlying *zap.Logger.
	Zap() *zap.Logger
	// Sugar returns the underlying *zap.SugaredLogger.
	Sugar() *zap.SugaredLogger
	// Sync flushes any buffered log entries.
	Sync() error
}

Logger is the interface for structured logging.

func FromContext

func FromContext(ctx context.Context) Logger

FromContext returns the Logger stored in the context, or the global logger if none.

func FromZap

func FromZap(zl *zap.Logger) Logger

FromZap wraps an existing *zap.Logger as a Logger.

func Global

func Global() Logger

Global returns the global logger instance.

func Named

func Named(name string) Logger

Named creates a child logger from the global logger with the given name.

func NewLogger

func NewLogger(config Config) Logger

NewLogger creates a new Logger from the given Config.

func With

func With(fields ...zap.Field) Logger

With creates a child logger from the global logger with additional fields.

func WithContext

func WithContext(logger Logger, ctx context.Context) Logger

WithContext creates a child logger with fields extracted from the context. It extracts trace_id, span_id, request_id, and user_id if present.

func WithError

func WithError(err error) Logger

WithError creates a child logger from the global logger with an error field.

func WithHook

func WithHook(logger Logger, hook Hook) Logger

WithHook creates a new Logger with the given hook attached.

func WithHooks

func WithHooks(logger Logger, hooks ...Hook) Logger

WithHooks creates a new Logger with multiple hooks attached.

Jump to

Keyboard shortcuts

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