logger

package
v0.0.0-...-fb81f76 Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

src/pkg/logger/config.go

src/pkg/logger/ctx_zap_logger.go

src/pkg/logger/manager.go

src/yogan/logger/stacktrace.go

src/pkg/logger/ctx_zap_logger_testing.go

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CaptureStacktrace

func CaptureStacktrace(skip int, depth int) string

CaptureStackTrace captures the current call stack (with depth limit support) skip: number of stack frames to skip (usually 2-3, skipping CaptureStacktrace and the caller itself) depth: maximum depth (0 means unlimited, recommended 5-10) Return the formatted stack string, one call frame per line

func CloseAll

func CloseAll()

CloseAll closes all Loggers (called when the application exits)

func Debug

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

Debug logging for DEBUG level logs

func DebugCtx

func DebugCtx(ctx context.Context, module string, msg string, fields ...zap.Field)

DebugCtx logs debug level logs (supports extracting traceID from context)

func Error

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

Record error level logs Usage: logger.Error("auth", "Login failed", zap.String("user", "admin")) Generate: logs/auth/auth-error-2024-12-19.log

func ErrorCtx

func ErrorCtx(ctx context.Context, module string, msg string, fields ...zap.Field)

ErrorCtx logs error level messages (supports extracting traceID from context) Usage: logger.ErrorCtx(ctx, "auth", "Login failed", zap.String("user", "admin")) If ctx contains a traceID, it will be automatically added to the log fields.

func Fatal

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

Fatal log at Fatal level (will call os.Exit(1))

func FatalCtx

func FatalCtx(ctx context.Context, module string, msg string, fields ...zap.Field)

FatalCtx logs at the Fatal level (calls os.Exit(1)) and supports extracting traceID from context

func Info

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

Info log for Info level logging Usage: logger.Info("order", "Order creation", zap.String("id", "001")) Generate: logs/order/order-info-2024-12-19.log

func InfoCtx

func InfoCtx(ctx context.Context, module string, msg string, fields ...zap.Field)

InfoCtx logs information level logs (supports extracting traceID from context) Usage: logger.InfoCtx(ctx, "order", "Order creation", zap.String("id", "001")) If ctx contains a traceID, it will automatically be added to the log fields.

func InitManager

func InitManager(cfg ManagerConfig)

Initialize Manager for global Logger manager (call once only)

func MustResetManager

func MustResetManager(cfg ManagerConfig)

func NewPrettyConsoleEncoder

func NewPrettyConsoleEncoder(cfg zapcore.EncoderConfig) zapcore.Encoder

Create a pretty console encoder (default single-line style)

func NewPrettyConsoleEncoderWithStyle

func NewPrettyConsoleEncoderWithStyle(cfg zapcore.EncoderConfig, style RenderStyle) zapcore.Encoder

Create a pretty console encoder with specified style

func Panic

func Panic(module string, msg string, fields ...zap.Field)

Panic log at panic level (triggers a panic)

func PanicCtx

func PanicCtx(ctx context.Context, module string, msg string, fields ...zap.Field)

PanicCtx logs panic level logs (triggers a panic, supports extracting traceID from context)

func ParseLevel

func ParseLevel(level string) zapcore.Level

ParseLevel parse log level string

func ReloadConfig

func ReloadConfig(newCfg ManagerConfig) error

ReloadConfig Hot reload configuration (recreate all Logger instances)

func Warn

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

Warn record Warn level log

func WarnCtx

func WarnCtx(ctx context.Context, module string, msg string, fields ...zap.Field)

WarnCtx logs warnings (supports extracting traceID from context)

Types

type Config

type Config struct {
	Level           string
	Development     bool
	Encoding        string // json, console or console_pretty
	ConsoleEncoding string

	EnableFile    bool
	EnableConsole bool

	// file name format configuration
	EnableLevelInFilename    bool   // Whether it includes level (info/error)
	EnableSequenceInFilename bool   // Whether it includes an ordinal number (01/02)
	SequenceNumber           string // Sequence number (e.g., "01")
	EnableDateInFilename     bool   // Does it contain a date
	DateFormat               string // Date format (default 2006-01-02)

	// File slicing configuration
	MaxSize    int  // Maximum size of individual file (MB)
	MaxBackups int  // Keep the number of old files
	MaxAge     int  // Number of days to retain
	Compress   bool // Whether to compress

	// stack configuration
	EnableCaller     bool
	EnableStacktrace bool
	StacktraceLevel  string // From which level to start recording the stack (default is error)
	StacktraceDepth  int    // Stack depth limit (0=unlimited, recommended 5-10)
	// contains filtered or unexported fields
}

Config module log configuration (for internal use)

func (*Config) Validate

func (c *Config) Validate() error

Validate configuration (implement config.Validator interface)

type CtxZapLogger

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

CtxZapLogger Context-aware Zap logger wrapper Design idea: module is bound during creation, only needs to pass ctx when used Reference: docs/085-logger-context-integration-analysis.md Solution 2.5 Note: The NewCtxZapLogger export function is no longer provided; use GetLogger() or CreateLogger() uniformly to obtain it.

func GetLogger

func GetLogger(moduleName string) *CtxZapLogger

GetLogger obtain the CtxZapLogger for the specified module (thread-safe, created as needed)

func NewCtxZapLogger

func NewCtxZapLogger(module string) *CtxZapLogger

newCtxZapLogger creates a context-aware logger (internal use, binds module on creation) Usage:

logger := logger.MustGetLogger("user") // for use in application layer logger := logger.MustGetLogger("yogan") // Use uniformly in the Yogan kernel logger.InfoCtx(ctx, "Create user", zap.String("name", "Zhang San"))

func WithFields

func WithFields(module string, fields ...zap.Field) *CtxZapLogger

WithFields creates a Logger for the specified module with preset fields Usage:

orderLogger := logger.WithFields("order", zap.String("service", "order-service"))

orderLogger.InfoCtx(ctx, "Order creation") // automatically includes service field

func (*CtxZapLogger) Debug

func (l *CtxZapLogger) Debug(msg string, fields ...zap.Field)

Debug logging for level debug (convenient method without needing context)

func (*CtxZapLogger) DebugCtx

func (l *CtxZapLogger) DebugCtx(ctx context.Context, msg string, fields ...zap.Field)

DebugCtx logs debug level logs (automatically extracts TraceID)

func (*CtxZapLogger) Error

func (l *CtxZapLogger) Error(msg string, fields ...zap.Field)

Records error level logs (a convenient method without needing context)

func (*CtxZapLogger) ErrorCtx

func (l *CtxZapLogger) ErrorCtx(ctx context.Context, msg string, fields ...zap.Field)

ErrorCtx logs error level logs (automatically extracts TraceID + optional stack)

func (*CtxZapLogger) GetZapLogger

func (l *CtxZapLogger) GetZapLogger() *zap.Logger

GetZapLogger Obtain the underlying *zap.Logger (for integration with third-party libraries) For example: etcd client.WithLogger(logger.GetZapLogger())

func (*CtxZapLogger) Info

func (l *CtxZapLogger) Info(msg string, fields ...zap.Field)

Info level logging (convenient method without needing context)

func (*CtxZapLogger) InfoCtx

func (l *CtxZapLogger) InfoCtx(ctx context.Context, msg string, fields ...zap.Field)

InfoCtx records Info level logs (automatically extracts TraceID)

func (*CtxZapLogger) Warn

func (l *CtxZapLogger) Warn(msg string, fields ...zap.Field)

Warn record Warn level log (a convenient method without requiring context)

func (*CtxZapLogger) WarnCtx

func (l *CtxZapLogger) WarnCtx(ctx context.Context, msg string, fields ...zap.Field)

WarnCtx logs warnings (automatically extracts TraceID)

func (*CtxZapLogger) With

func (l *CtxZapLogger) With(fields ...zap.Field) *CtxZapLogger

Returns a new Logger with preset fields (supports method chaining) Usage:

orderLogger := logger.With(zap.Int64("order_id", 123))

orderLogger.InfoCtx(ctx, "Order processing") // Automatically includes order_id

type GinLogWriter

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

GinLogWriter Gin log adapter (implements the io.Writer interface) Adapt Gin's text logs to a custom Logger component

func NewGinLogWriter

func NewGinLogWriter(module string) *GinLogWriter

Create Gin log adapter module: log module name, used to distinguish logs from different sources of Gin "gin-route": routing registration logs "gin-internal": other kernel logs

func (*GinLogWriter) Write

func (w *GinLogWriter) Write(p []byte) (n int, err error)

Implement the io.Writer interface The Gin framework will call this method to write logs Convert Gin's text logs to structured log output

type GormLogger

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

GormLogger custom GORM Logger (implements the gorm logger.Interface interface) Use the gorm_sql module uniformly to log all database logs

func NewGormLogger

func NewGormLogger(cfg GormLoggerConfig) *GormLogger

Create custom GORM Logger

func (*GormLogger) Error

func (l *GormLogger) Error(ctx context.Context, msg string, data ...interface{})

Error level logging (implements gorm Logger Interface)

func (*GormLogger) Info

func (l *GormLogger) Info(ctx context.Context, msg string, data ...interface{})

Info level log recording (implements gorm logger.Interface)

func (*GormLogger) LogMode

LogMode sets the log level (implements gorm logger.Interface)

func (*GormLogger) Trace

func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error)

Record SQL execution log (implement gorm Logger Interface) This is the most important method for logging all SQL executions

func (*GormLogger) Warn

func (l *GormLogger) Warn(ctx context.Context, msg string, data ...interface{})

Warn record Warn level log (implement gorm Logger Interface)

type GormLoggerConfig

type GormLoggerConfig struct {
	SlowThreshold time.Duration       // Slow query threshold, default 200ms
	LogLevel      gormlogger.LogLevel // Log level
	EnableAudit   bool                // Whether to enable SQL auditing, default is true
}

GormLoggerConfig GORM Logger configuration

func DefaultGormLoggerConfig

func DefaultGormLoggerConfig() GormLoggerConfig

DefaultGormLoggerConfig default configuration

type LogEntry

type LogEntry struct {
	Level   string
	Message string
	TraceID string
	Fields  map[string]interface{}
}

Log Entry

type Manager

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

Manager Logger (manages multiple Logger instances)

func NewManager

func NewManager(cfg ManagerConfig) *Manager

NewManager creates independent Manager instances (supports multi-instance scenarios) Usage:

appManager := logger.NewManager(cfg)
appManager.Info("order", "Order creation")

NewManager creates independent Manager instances zero-valued fields in cfg will be automatically filled with default values

func (*Manager) CloseAll

func (m *Manager) CloseAll()

CloseAll closes all Loggers (called when the application exits) will refresh the buffer and close all file handles

func (*Manager) Debug

func (m *Manager) Debug(module string, msg string, fields ...zap.Field)

Debug logging for Debug level logs

func (*Manager) DebugCtx

func (m *Manager) DebugCtx(ctx context.Context, module string, msg string, fields ...zap.Field)

DebugCtx logs debug level logs (supports extracting traceID from context)

func (*Manager) Error

func (m *Manager) Error(module string, msg string, fields ...zap.Field)

Record error level logs

func (*Manager) ErrorCtx

func (m *Manager) ErrorCtx(ctx context.Context, module string, msg string, fields ...zap.Field)

ErrorCtx logs error level messages (supports extracting traceID from context)

func (*Manager) Fatal

func (m *Manager) Fatal(module string, msg string, fields ...zap.Field)

Fatal logs are recorded at the fatal level (will call os.Exit(1))

func (*Manager) FatalCtx

func (m *Manager) FatalCtx(ctx context.Context, module string, msg string, fields ...zap.Field)

FatalCtx logs at the Fatal level (calls os.Exit(1)) and supports extracting traceID from context

func (*Manager) GetLogger

func (m *Manager) GetLogger(moduleName string) *CtxZapLogger

GetLogger obtain a thread-safe CtxZapLogger for the specified module (created as needed) The returned Logger automatically includes a module field

func (*Manager) Info

func (m *Manager) Info(module string, msg string, fields ...zap.Field)

Info log for Info level logging

func (*Manager) InfoCtx

func (m *Manager) InfoCtx(ctx context.Context, module string, msg string, fields ...zap.Field)

InfoCtx logs info level logs (supports extracting traceID from context)

func (*Manager) Panic

func (m *Manager) Panic(module string, msg string, fields ...zap.Field)

Panic log at panic level (will trigger a panic)

func (*Manager) PanicCtx

func (m *Manager) PanicCtx(ctx context.Context, module string, msg string, fields ...zap.Field)

PanicCtx logs at the Panic level (triggers a panic and supports extracting traceID from context)

func (*Manager) ReloadConfig

func (m *Manager) ReloadConfig(newCfg ManagerConfig) error

ReloadConfig hot reload configuration (recreate all Logger instances)

func (*Manager) Warn

func (m *Manager) Warn(module string, msg string, fields ...zap.Field)

Warn Record Warn level log

func (*Manager) WarnCtx

func (m *Manager) WarnCtx(ctx context.Context, module string, msg string, fields ...zap.Field)

WarnCtx logs warnings (supports extracting traceID from context)

func (*Manager) WithFields

func (m *Manager) WithFields(module string, fields ...zap.Field) *CtxZapLogger

WithFields creates a Logger for the specified module with preset fields

type ManagerConfig

type ManagerConfig struct {
	BaseLogDir               string `mapstructure:"base_log_dir"` // Fix root directory (default logs/)
	Level                    string `mapstructure:"level"`
	AppName                  string `mapstructure:"app_name"` // Application name (automatically injects all logs, including null values)
	Encoding                 string `mapstructure:"encoding"`
	ConsoleEncoding          string `mapstructure:"console_encoding"`
	EnableConsole            bool   `mapstructure:"enable_console"`
	EnableLevelInFilename    bool   `mapstructure:"enable_level_in_filename"`
	EnableSequenceInFilename bool   `mapstructure:"enable_sequence_in_filename"`
	EnableDateInFilename     bool   `mapstructure:"enable_date_in_filename"`
	DateFormat               string `mapstructure:"date_format"`
	MaxSize                  int    `mapstructure:"max_size"`
	MaxBackups               int    `mapstructure:"max_backups"`
	MaxAge                   int    `mapstructure:"max_age"`
	Compress                 bool   `mapstructure:"compress"`
	EnableCaller             bool   `mapstructure:"enable_caller"`
	EnableStacktrace         bool   `mapstructure:"enable_stacktrace"`
	StacktraceLevel          string `mapstructure:"stacktrace_level"`
	StacktraceDepth          int    `mapstructure:"stacktrace_depth"` // stack depth (0=unlimited)
	LoggerName               string `mapstructure:"logger_name"`
	ModuleNumber             int    `mapstructure:"module_number"`

	// Render style configuration (valid for console_pretty encoder only)
	// Optional values: single_line (default), key_value
	RenderStyle string `mapstructure:"render_style"`

	// Trace ID configuration
	EnableTraceID    bool   `mapstructure:"enable_trace_id"`     // Whether to enable automatic extraction of traceID
	TraceIDKey       string `mapstructure:"trace_id_key"`        // the key in context (default "trace_id")
	TraceIDFieldName string `mapstructure:"trace_id_field_name"` // Log field name (default "trace_id")
}

ManagerConfig global manager configuration (shared by all modules)

func DefaultManagerConfig

func DefaultManagerConfig() ManagerConfig

Returns default manager configuration

func (*ManagerConfig) ApplyDefaults

func (c *ManagerConfig) ApplyDefaults()

ApplyDefaults fills zero-valued fields with default values (in-place modification) For handling missing or zero-valued fields in configuration files

func (ManagerConfig) Validate

func (c ManagerConfig) Validate() error

Validate ManagerConfig configuration

type PrettyConsoleEncoder

type PrettyConsoleEncoder struct {
	*zapcore.EncoderConfig
	// contains filtered or unexported fields
}

PrettyConsoleEncoder enhanced console encoder Supports multiple rendering styles: single line, key-value pairs, etc.

func (*PrettyConsoleEncoder) AddArray

func (enc *PrettyConsoleEncoder) AddArray(key string, arr zapcore.ArrayMarshaler) error

func (*PrettyConsoleEncoder) AddBinary

func (enc *PrettyConsoleEncoder) AddBinary(key string, value []byte)

func (*PrettyConsoleEncoder) AddBool

func (enc *PrettyConsoleEncoder) AddBool(key string, value bool)

func (*PrettyConsoleEncoder) AddByteString

func (enc *PrettyConsoleEncoder) AddByteString(key string, value []byte)

func (*PrettyConsoleEncoder) AddComplex64

func (enc *PrettyConsoleEncoder) AddComplex64(key string, value complex64)

func (*PrettyConsoleEncoder) AddComplex128

func (enc *PrettyConsoleEncoder) AddComplex128(key string, value complex128)

func (*PrettyConsoleEncoder) AddDuration

func (enc *PrettyConsoleEncoder) AddDuration(key string, value time.Duration)

func (*PrettyConsoleEncoder) AddFloat32

func (enc *PrettyConsoleEncoder) AddFloat32(key string, value float32)

func (*PrettyConsoleEncoder) AddFloat64

func (enc *PrettyConsoleEncoder) AddFloat64(key string, value float64)

func (*PrettyConsoleEncoder) AddInt

func (enc *PrettyConsoleEncoder) AddInt(key string, value int)

func (*PrettyConsoleEncoder) AddInt8

func (enc *PrettyConsoleEncoder) AddInt8(key string, value int8)

func (*PrettyConsoleEncoder) AddInt16

func (enc *PrettyConsoleEncoder) AddInt16(key string, value int16)

func (*PrettyConsoleEncoder) AddInt32

func (enc *PrettyConsoleEncoder) AddInt32(key string, value int32)

func (*PrettyConsoleEncoder) AddInt64

func (enc *PrettyConsoleEncoder) AddInt64(key string, value int64)

func (*PrettyConsoleEncoder) AddObject

func (enc *PrettyConsoleEncoder) AddObject(key string, obj zapcore.ObjectMarshaler) error

func (*PrettyConsoleEncoder) AddReflected

func (enc *PrettyConsoleEncoder) AddReflected(key string, value interface{}) error

func (*PrettyConsoleEncoder) AddString

func (enc *PrettyConsoleEncoder) AddString(key, value string)

func (*PrettyConsoleEncoder) AddTime

func (enc *PrettyConsoleEncoder) AddTime(key string, value time.Time)

func (*PrettyConsoleEncoder) AddUint

func (enc *PrettyConsoleEncoder) AddUint(key string, value uint)

func (*PrettyConsoleEncoder) AddUint8

func (enc *PrettyConsoleEncoder) AddUint8(key string, value uint8)

func (*PrettyConsoleEncoder) AddUint16

func (enc *PrettyConsoleEncoder) AddUint16(key string, value uint16)

func (*PrettyConsoleEncoder) AddUint32

func (enc *PrettyConsoleEncoder) AddUint32(key string, value uint32)

func (*PrettyConsoleEncoder) AddUint64

func (enc *PrettyConsoleEncoder) AddUint64(key string, value uint64)

func (*PrettyConsoleEncoder) AddUintptr

func (enc *PrettyConsoleEncoder) AddUintptr(key string, value uintptr)

func (*PrettyConsoleEncoder) Clone

func (enc *PrettyConsoleEncoder) Clone() zapcore.Encoder

Clone the encoder

func (*PrettyConsoleEncoder) EncodeEntry

func (enc *PrettyConsoleEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error)

EncodeEntry encode log entry (distribute based on rendering style)

func (*PrettyConsoleEncoder) OpenNamespace

func (enc *PrettyConsoleEncoder) OpenNamespace(key string)

type RenderStyle

type RenderStyle string

RenderStyle logging rendering style

const (
	// Render single line (default)
	// Format: [🔵INFO] | 2025-12-23T01:10:01.165+0800 | message | [module] | file:line | trace-id | {"key":"value"}
	RenderStyleSingleLine RenderStyle = "single_line"

	// RenderStyleKeyValue Key-value pair rendering (multi-line, suitable for small screens)
	// Format:
	//   🟢 DEBU | 2025-12-23 01:10:01.165
	//     trace: -
	//     module: gin-route
	//     caller: logger/manager.go:316
	//     message: [GIN-debug] GET / --> ...
	RenderStyleKeyValue RenderStyle = "key_value"

	// RenderStyleModernCompact Modern compact style
	// Format: 14:30:45 │ INFO  │ HTTP server started                          │ yogan      {"key":"value"}
	// Features: time-saving, Box Drawing separators, fixed column width, clear hierarchy
	RenderStyleModernCompact RenderStyle = "modern_compact"
)

func ParseRenderStyle

func ParseRenderStyle(s string) RenderStyle

ParseRenderStyle parse rendering style string

type TestCtxLogger

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

TestCtxLogger context-aware logger for testing purposes Log to memory for convenient verification in unit tests

func NewTestCtxLogger

func NewTestCtxLogger() *TestCtxLogger

Create test Logger (log to memory) Usage:

testLogger := logger.NewTestCtxLogger()
svc := user.NewService(repo, testLogger)
svc.CreateUser(ctx, "test", "[email protected]", 25)
assert.True(t, testLogger.HasLog("INFO", "Create user"))

func (*TestCtxLogger) Clear

func (t *TestCtxLogger) Clear()

Clear logs (for test isolation)

func (*TestCtxLogger) CountLogs

func (t *TestCtxLogger) CountLogs(level string) int

CountLogs counts the number of logs at a specified level

func (*TestCtxLogger) DebugCtx

func (t *TestCtxLogger) DebugCtx(ctx context.Context, msg string, fields ...zap.Field)

DebugCtx logs debug level logs (records to memory)

func (*TestCtxLogger) ErrorCtx

func (t *TestCtxLogger) ErrorCtx(ctx context.Context, msg string, fields ...zap.Field)

ErrorCtx logs error level logs (records to memory)

func (*TestCtxLogger) HasLog

func (t *TestCtxLogger) HasLog(level, message string) bool

Check if a log with the specified level and message exists

func (*TestCtxLogger) HasLogWithField

func (t *TestCtxLogger) HasLogWithField(level, message, fieldKey string, fieldValue interface{}) bool

Checks if a log with specified level, message, and field exists

func (*TestCtxLogger) HasLogWithTraceID

func (t *TestCtxLogger) HasLogWithTraceID(level, message, traceID string) bool

Checks if a log with specified level, message, and TraceID exists

func (*TestCtxLogger) InfoCtx

func (t *TestCtxLogger) InfoCtx(ctx context.Context, msg string, fields ...zap.Field)

InfoCtx logs info level logs (recorded in memory)

func (*TestCtxLogger) Logs

func (t *TestCtxLogger) Logs() []LogEntry

Logs Retrieve all logs (for detailed verification)

func (*TestCtxLogger) WarnCtx

func (t *TestCtxLogger) WarnCtx(ctx context.Context, msg string, fields ...zap.Field)

WarnCtx logs Warn level messages (stored in memory)

func (*TestCtxLogger) With

func (t *TestCtxLogger) With(fields ...zap.Field) *TestCtxLogger

Returns a new Logger with preset fields (for testing)

Jump to

Keyboard shortcuts

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