logging

package
v1.1.8 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2026 License: MIT Imports: 6 Imported by: 0

README

Logging (日志系统)

pkg/logging 提供了 GoRAG 框架的统一日志接口及其工业级实现。

设计哲学

在工业级 RAG 系统中,日志不仅是调试工具,更是审计和排障的关键依据。本包采用了平权化接口设计

  1. 接口隔离:框架核心只依赖 Logger 接口,不绑定任何具体实现。
  2. 渐进式升级:提供从极简控制台打印到高性能滚动日志的全量支持。

核心接口

type Logger interface {
    Info(msg string, fields ...map[string]any)
    Error(msg string, err error, fields ...map[string]any)
    Debug(msg string, fields ...map[string]any)
    Warn(msg string, fields ...map[string]any)
}

我们提供的实现

1. ConsoleLogger (控制台日志)
  • 用途:本地开发、单元测试。
  • 特点:直接输出到 stdout,带标准时间戳。
  • 初始化logging.DefaultConsoleLogger()
2. ZapLogger (工业级高性能日志)
  • 用途:生产环境、高并发场景。
  • 特点
    • 基于 uber-go/zap,极低的内存分配和极高的吞吐量。
    • 自动滚动 (Rotation):集成 lumberjack,支持基于文件大小、保留天数自动切割日志,防止磁盘爆满。
    • 日志压缩:旧日志自动 gzip 压缩。
    • 多路输出 (Tee):支持同时输出 JSON 格式(用于日志采集系统如 ELK)和控制台高亮格式。
  • 初始化
    logger := logging.DefaultZapLogger(logging.ZapConfig{
        Filename:   "logs/gorag.log",
        MaxSize:    100,  // MB
        MaxAge:     30,   // Days
        MaxBackups: 7,    // 备份数
        Compress:   true,
        Console:    true, // 同时打印到控制台
    })
    
3. NoopLogger (静默日志)
  • 用途:不需要任何日志输出的极端性能场景或基准测试。

在 GoRAG 中快速集成

建议通过 indexer 的 Option 直接注入:

// 生产环境推荐配置
idx, _ := indexer.NewBuilder().
    WithZapLogger("./data/logs/app.log", 500, 7, 5, false).
    Build()

Documentation

Overview

Package logging provides structured logging capabilities for the goRAG framework. It offers a simple, flexible logging interface with support for multiple log levels, file and console output, and structured field logging.

The package provides two main implementations:

  • Console logger: Outputs to stdout with minimal formatting
  • File logger: Writes to a file with configurable log level
  • No-op logger: Discards all log output (useful for testing)

Example usage:

// Create a console logger
logger := logging.DefaultConsoleLogger()
logger.Info("Application started", map[string]any{"version": "1.0"})

// Create a file logger with debug level
logger, err := logging.DefaultFileLogger("app.log", logging.WithLevel(logging.DEBUG))
if err != nil {
    log.Fatal(err)
}
defer logger.(*logging.defaultLogger).Close()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Level added in v1.1.3

type Level int

Level represents the severity level of a log message. Log levels are ordered from least to most severe: DEBUG < INFO < WARN < ERROR.

const (
	// DEBUG level is for detailed debugging information.
	// Typically enabled during development or troubleshooting.
	DEBUG Level = iota

	// INFO level is for general operational information.
	// Suitable for production use to track normal operations.
	INFO

	// WARN level is for warning messages that indicate potential issues.
	// Not errors, but situations that might need attention.
	WARN

	// ERROR level is for error messages indicating failures.
	// Should be used for errors that affect operation but are recoverable.
	ERROR
)

Log level constants define the severity of log messages. Messages with a level below the configured threshold will not be logged.

func (Level) String added in v1.1.3

func (l Level) String() string

String returns the string representation of the log level. Returns "DEBUG", "INFO", "WARN", "ERROR", or "UNKNOWN" for invalid levels.

type Logger

type Logger interface {
	// Info logs an informational message.
	// Use for general operational messages.
	//
	// Parameters:
	//   - msg: The log message
	//   - fields: Optional structured fields (can be omitted or nil)
	Info(msg string, fields ...map[string]any)

	// Error logs an error message with the associated error.
	// The error is automatically included in the fields.
	//
	// Parameters:
	//   - msg: The log message describing the error context
	//   - err: The error that occurred (can be nil)
	//   - fields: Optional additional structured fields
	Error(msg string, err error, fields ...map[string]any)

	// Debug logs a debug message.
	// Use for detailed information useful during development.
	//
	// Parameters:
	//   - msg: The debug message
	//   - fields: Optional structured fields
	Debug(msg string, fields ...map[string]any)

	// Warn logs a warning message.
	// Use for potentially problematic situations that aren't errors.
	//
	// Parameters:
	//   - msg: The warning message
	//   - fields: Optional structured fields
	Warn(msg string, fields ...map[string]any)
}

Logger defines the interface for structured logging. Implementations should support multiple log levels and structured field logging.

All methods accept optional fields as map[string]any for structured logging. Example:

logger.Info("User logged in", map[string]any{
    "user_id": 123,
    "ip": "192.168.1.1",
})

func DefaultConsoleLogger added in v1.1.3

func DefaultConsoleLogger() Logger

DefaultConsoleLogger creates a logger that writes to stdout. It uses INFO level by default and outputs without timestamps or prefixes.

Returns:

  • Logger: A logger writing to standard output

Example:

logger := logging.DefaultConsoleLogger()
logger.Info("Server started on port 8080")

func DefaultFileLogger added in v1.1.3

func DefaultFileLogger(filePath string, opts ...Option) (Logger, error)

DefaultFileLogger creates a logger that writes to a file. The file is created if it doesn't exist, and appended to if it does.

Parameters:

  • filePath: Path to the log file
  • opts: Optional configuration options (e.g., WithLevel)

Returns:

  • Logger: A logger writing to the specified file
  • error: Any error that occurred while opening the file

Example:

logger, err := logging.DefaultFileLogger("app.log", logging.WithLevel(logging.DEBUG))
if err != nil {
    log.Fatal(err)
}
defer logger.(*logging.defaultLogger).Close()

func DefaultNoopLogger added in v1.1.3

func DefaultNoopLogger() Logger

DefaultNoopLogger creates a logger that discards all output. Useful for testing or when logging should be disabled.

Returns:

  • Logger: A logger that does nothing

func DefaultZapLogger added in v1.1.3

func DefaultZapLogger(cfg ZapConfig) Logger

DefaultZapLogger creates a high-performance logger using uber-go/zap with lumberjack for log rotation.

type Option added in v1.1.3

type Option func(*defaultLogger)

Option is a function that configures a defaultLogger.

func WithLevel added in v1.1.3

func WithLevel(level Level) Option

WithLevel returns an Option that sets the minimum log level. Messages below this level will not be logged.

Parameters:

  • level: The minimum log level to enable

Returns:

  • Option: A configuration function for the logger

Example:

logger, _ := logging.DefaultFileLogger("app.log", logging.WithLevel(logging.DEBUG))

type ZapConfig added in v1.1.3

type ZapConfig struct {
	// Filename is the file to write logs to.
	Filename string
	// MaxSize is the maximum size in megabytes of the log file before it gets rotated.
	MaxSize int
	// MaxBackups is the maximum number of old log files to retain.
	MaxBackups int
	// MaxAge is the maximum number of days to retain old log files.
	MaxAge int
	// Compress determines if the rotated log files should be compressed using gzip.
	Compress bool
	// Console specifies if logs should also be printed to standard output.
	Console bool
}

ZapConfig defines the options for the Zap rolling logger

Jump to

Keyboard shortcuts

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