Rust日志处理库aya-log-common的使用:高效日志记录与通用日志功能实现

Rust日志处理库aya-log-common的使用:高效日志记录与通用日志功能实现

安装

在项目目录中运行以下Cargo命令:

cargo add aya-log-common

或者在你的Cargo.toml中添加以下行:

aya-log-common = "0.1.15"

基本使用示例

aya-log-common是一个为Rust项目提供高效日志记录和通用日志功能的库。以下是基本使用示例:

use aya_log_common::{write_record, Level, Record};

fn main() {
    // 创建一个日志记录
    let record = Record {
        level: Level::Info,
        target: "my_app",
        args: "This is an info message",
    };
    
    // 写入日志记录
    write_record(&record).expect("Failed to write log record");
}

完整示例Demo

下面是一个更完整的示例,展示了如何使用aya-log-common进行不同级别的日志记录:

use aya_log_common::{write_record, Level, Record};

fn main() {
    // 不同级别的日志记录
    let records = vec![
        Record {
            level: Level::Trace,
            target: "my_app::module1",
            args: "Detailed trace information",
        },
        Record {
            level: Level::Debug,
            target: "my_app::module2",
            args: "Debugging information",
        },
        Record {
            level: Level::Info,
            target: "my_app",
            args: "Application started successfully",
        },
        Record {
            level: Level::Warn,
            target: "my_app::network",
            args: "Connection timeout, retrying...",
        },
        Record {
            level: Level::Error,
            target: "my_app::database",
            args: "Failed to connect to database",
        },
    ];

    // 写入所有日志记录
    for record in records {
        write_record(&record).expect("Failed to write log record");
    }

    // 带格式的日志消息
    let formatted_record = Record {
        level: Level::Info,
        target: "my_app::stats",
        args: format!("Processed {} items in {:.2} seconds", 42, 3.1415),
    };
    write_record(&formatted_record).expect("Failed to write formatted log");
}

关键特性

  1. 高效日志记录:aya-log-common经过优化,对应用程序性能影响最小
  2. 多日志级别支持:包括Trace、Debug、Info、Warn和Error级别
  3. 结构化日志:支持带目标(target)的分类日志
  4. 简单API:简洁的Record结构和write_record函数

许可证

aya-log-common采用MIT或Apache-2.0双重许可证。


1 回复

Rust日志处理库aya-log-common的使用指南

概述

aya-log-common 是一个高效的 Rust 日志处理库,专为需要通用日志功能的应用程序设计。它提供了简单易用的接口和灵活的配置选项,适合各种规模的 Rust 项目。

主要特性

  • 高性能日志记录
  • 多日志级别支持
  • 可定制的日志格式
  • 线程安全的实现
  • 易于集成到现有项目

安装

在 Cargo.toml 中添加依赖:

[dependencies]
aya-log-common = "0.1"

基本使用方法

初始化日志系统

use aya_log_common::{Logger, LogLevel};

fn main() {
    // 初始化日志记录器,设置日志级别为Info
    let logger = Logger::new(LogLevel::Info);
    
    logger.info("Application started");
}

记录不同级别的日志

logger.trace("This is a trace message");
logger.debug("Debug information");
logger.info("Informational message");
logger.warn("Warning message");
logger.error("Error occurred");

高级用法

自定义日志格式

use aya_log_common::{Logger, LogLevel, LogFormat};

let logger = Logger::new(LogLevel::Debug)
    .with_format(LogFormat::Custom(|level, message| {
        format!("[{}] [{}] {}", chrono::Local::now().format("%Y-%m-%d %H:%M:%S"), level, message)
    }));

logger.info("Custom formatted log message");

日志输出到文件

use aya_log_common::{Logger, LogLevel, LogOutput};

let logger = Logger::new(LogLevel::Info)
    .with_output(LogOutput::File("app.log".into()));

logger.info("This will be written to app.log");

多输出目标

use aya_log_common::{Logger, LogLevel, LogOutput};

let logger = Logger::new(LogLevel::Info)
    .with_output(LogOutput::Stdout)
    .with_output(LogOutput::File("app.log".into()));

logger.info("This will go to both stdout and the log file");

实际应用示例

use aya_log_common::{Logger, LogLevel};

struct Application {
    logger: Logger,
}

impl Application {
    fn new() -> Self {
        let logger = Logger::new(LogLevel::Debug);
        logger.info("Application instance created");
        Application { logger }
    }

    fn process_data(&self, data: &str) {
        self.logger.debug(&format!("Processing data: {}", data));
        
        if data.is_empty() {
            self.logger.warn("Received empty data");
            return;
        }
        
        // 处理逻辑...
        self.logger.info("Data processed successfully");
    }
}

fn main() {
    let app = Application::new();
    app.process_data("sample data");
    app.process_data("");
}

性能建议

  1. 在生产环境中使用 LogLevel::Info 或更高以减少日志量
  2. 对于性能关键路径,考虑使用 logger.is_enabled(LogLevel::Debug) 检查后再构造复杂日志消息
  3. 批量日志操作可以使用 logger.batch() 方法

完整示例代码

use aya_log_common::{Logger, LogLevel, LogFormat, LogOutput};
use std::thread;
use std::time::Duration;

// 自定义日志处理器结构体
struct LogProcessor {
    logger: Logger,
}

impl LogProcessor {
    // 创建新的LogProcessor实例
    fn new(level: LogLevel) -> Self {
        let logger = Logger::new(level)
            .with_format(LogFormat::Custom(|level, msg| {
                format!("[MyApp][{}] {}", level, msg)
            }))
            .with_output(LogOutput::Stdout)
            .with_output(LogOutput::File("application.log".into()));
            
        logger.info("LogProcessor initialized");
        LogProcessor { logger }
    }

    // 模拟处理任务
    fn perform_task(&self, task_id: u32) {
        self.logger.debug(&format!("Starting task {}", task_id));
        
        // 模拟工作
        thread::sleep(Duration::from_millis(100));
        
        if task_id % 5 == 0 {
            self.logger.warn(&format!("Task {} took longer than expected", task_id));
        }
        
        self.logger.info(&format!("Completed task {}", task_id));
    }
    
    // 批量处理任务
    fn batch_process(&self, count: u32) {
        if self.logger.is_enabled(LogLevel::Debug) {
            self.logger.debug("Starting batch processing");
        }
        
        self.logger.batch(|| {
            for i in 0..count {
                self.logger.info(&format!("Processing item {}", i));
            }
        });
        
        self.logger.info("Batch processing completed");
    }
}

fn main() {
    // 初始化日志处理器
    let processor = LogProcessor::new(LogLevel::Debug);
    
    // 执行单个任务
    processor.perform_task(1);
    
    // 执行多个任务
    for i in 2..=10 {
        processor.perform_task(i);
    }
    
    // 执行批量处理
    processor.batch_process(5);
    
    // 错误处理示例
    match std::fs::read_to_string("nonexistent.txt") {
        Ok(_) => processor.logger.info("File read successfully"),
        Err(e) => processor.logger.error(&format!("Failed to read file: {}", e)),
    }
}

总结

aya-log-common 提供了一个简单而强大的日志解决方案,适用于大多数 Rust 应用程序。通过灵活的配置选项和直观的 API,开发者可以轻松实现高效的日志记录功能。完整示例展示了如何在实际应用中使用该库,包括初始化、自定义格式、多输出目标、批量处理等高级功能。

回到顶部