Skip to main content

Crate asynclog

Crate asynclog 

Source
Expand description

§asynclog async logging implementation

§Overview

asynclog is a high-performance, asynchronous logging library designed for Rust applications. It offers flexible configuration options, including log level control, file output, console output, asynchronous writing, and support for custom plugins and filters.

§Key Features

  • Log Level Control: Supports standard log levels (trace, debug, info, warn, error, off).
  • Multiple Output Targets:
    • Console output (with ANSI color support)
    • File output (with automatic log rotation)
  • Asynchronous Writing: Efficient log writing via background tasks or thread pools.
  • Custom Plugins: Allows extending log output behavior.
  • Custom Filters: Supports conditional filtering of log records.
  • Cache Optimization: Internal caching reduces memory allocation overhead.
  • Cross-Platform Compatibility: Supports both tokio and synchronous modes.

§Quick Start

§1. Add Dependency

Add the following to your Cargo.toml:

[dependencies]
asynclog = { version = "0.1", features = ["tokio"] }

If asynchronous support is not needed, remove features = ["tokio"].

§2. Initialize Logging

use asynclog::{LogOptions, parse_level};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Build log configuration
    let opts = LogOptions::new()
        .level(parse_level("info")?) // Set log level to info
        .log_file("app.log".to_string()) // Output to file
        .log_file_max_str("10M")? // Maximum log file size: 10MB
        .use_console(true) // Enable console output
        .use_async(true); // Enable asynchronous writing

    // Initialize the logging system
    opts.builder()?;

    // Start logging
    log::info!("Application started");
    log::debug!("This is a debug message");
    log::error!("Something went wrong!");

    Ok(())
}

§Configuration Details

§LogOptions Struct

The LogOptions struct provides rich configuration options for customizing logging behavior.

§Method List
Method NameParameter TypeDescription
levellog::LevelFilterSets the minimum log level
log_fileStringSets the log file path
log_file_maxu32Sets the maximum log file size (bytes)
use_consoleboolEnables/disables console output
use_asyncboolEnables/disables asynchronous writing
pluginBox<dyn Write + Send>Registers a custom log plugin
filterimpl CustomFilterRegisters a custom log filter
level_str&strSets log level using a string
log_file_max_str&strSets max log file size using a string

§Feature Details

§1. Log Levels

Supported standard log levels include:

  • trace: Most detailed debugging information
  • debug: Debugging information
  • info: General information
  • warn: Warning messages
  • error: Error messages
  • off: Disable all logging

You can dynamically adjust the log level for specific modules using the set_level function:

asynclog::set_level("my_module".to_string(), log::LevelFilter::Warn);

§2. Asynchronous Writing

When enabled, logs are processed by background tasks without blocking the main thread. Ideal for high-concurrency scenarios.

let opts = LogOptions::new().use_async(true);

§3. Log File Rotation

When the log file reaches its maximum size, it is automatically renamed with a .bak suffix, and a new file is created.

let opts = LogOptions::new().log_file_max(10 * 1024 * 1024); // 10MB

§4. Custom Plugins

Plugins can intercept each log record and execute custom logic. For example, sending logs to a remote server:

use std::io::Write;

struct RemoteLogger;

impl Write for RemoteLogger {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        // Send log to remote server
        println!("Sending log: {}", String::from_utf8_lossy(buf));
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

let opts = LogOptions::new().plugin(RemoteLogger);

§5. Custom Filters

Implement the CustomFilter trait to filter logs based on arbitrary conditions:

struct KeywordFilter(String);

impl CustomFilter for KeywordFilter {
    fn enabled(&self, record: &log::Record) -> bool {
        !record.args().to_string().contains(&self.0)
    }
}

let opts = LogOptions::new().filter(KeywordFilter("secret".to_string()));

§Notes

  • In debug mode, calling the initialization function more than once will cause the program to crash.
  • The log file path must have write permissions.
  • Asynchronous mode depends on the tokio runtime; ensure proper integration in your project.

Structs§

LogOptions
LogOptions is a struct that holds the configuration for the logger.
TimeBuf

Traits§

CustomFilter
custom log filter

Functions§

init_log
It creates a new logger, initializes it, and then sets it as the global logger
parse_level
It takes a string and returns a Result of a log::LevelFilter
parse_size
It parses a string into a number, The units that can be used are k/m/g
set_level
Set log level for target