secra-logger 3.0.3

一个生产级的 Rust 日志系统库,基于 tracing 生态系统构建,支持结构化 JSON 日志、文件滚动、UTC+8 时区等特性
Documentation
use std::path::PathBuf;

/// 日志格式
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogFormat {
    /// JSON 格式
    Json,
    /// 人类可读格式
    Human,
}

/// 轮转策略
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RotationStrategy {
    /// 按天轮转
    Daily,
    /// 按大小轮转(当前实现会降级为按小时轮转,避免不可用)
    Size(usize),
}

/// 日志轮转配置
#[derive(Debug, Clone)]
pub struct LogRotationConfig {
    /// 轮转策略
    pub strategy: RotationStrategy,
    /// 保留文件数量(当前 `tracing-appender` 不支持自动清理旧文件;保留字段用于兼容/未来扩展)
    pub max_files: usize,
}

/// 日志配置
#[derive(Debug, Clone)]
pub struct LogConfig {
    /// 日志级别(用于应用模式的 EnvFilter 默认 directive)
    pub level: tracing::Level,

    /// 是否启用控制台输出
    pub console_output: bool,
    /// 控制台输出格式
    pub console_format: LogFormat,
    /// 控制台是否启用颜色
    pub console_colors: bool,
    /// 控制台是否显示 target
    pub console_show_target: bool,
    /// 控制台是否显示文件
    pub console_show_file: bool,
    /// 控制台是否显示行号
    pub console_show_line: bool,

    /// 是否启用文件输出
    pub file_output: bool,
    /// 日志文件路径(目录 + 文件名基准;实际会由 appender 生成带日期/小时的文件)
    pub log_file: Option<PathBuf>,
    /// 文件输出格式
    pub file_format: LogFormat,
    /// 日志轮转配置
    pub rotation: LogRotationConfig,
}

impl Default for LogRotationConfig {
    fn default() -> Self {
        Self {
            strategy: RotationStrategy::Daily,
            max_files: 7,
        }
    }
}

impl Default for LogConfig {
    fn default() -> Self {
        Self {
            level: tracing::Level::INFO,
            console_output: true,
            console_format: LogFormat::Human,
            console_colors: true,
            console_show_target: true,
            console_show_file: true,
            console_show_line: true,
            file_output: false,
            log_file: None,
            file_format: LogFormat::Json,
            rotation: LogRotationConfig::default(),
        }
    }
}