#log #progress #multi-thread #config #logging #tokio

mtlog-tokio

Scoped logging for tokio runtimes with support for log files

1 unstable release

0.1.0 Oct 16, 2024

#951 in Concurrency

Download history 144/week @ 2024-10-16 4/week @ 2024-10-23

148 downloads per month

GPL-3.0-only

17KB
305 lines

mtlog-tokio

Scoped logging for tokio runtimes with support for log files.

Usage

// Cargo.toml
...
[dependencies]
mtlog-tokio = "0.1.0"
tokio = {version = "1.40.0", features = ["full"]}
use mtlog_tokio::logger_config;

#[tokio::main]
async fn main() {
    logger_config()
        .scope_global(async move {
            log::info!("Hello, world!");
            tokio::time::sleep(std::time::Duration::from_millis(1)).await; // wait for log to flush
        }).await;
}

Multi-threaded logging

use mtlog_tokio::logger_config;

#[tokio::main]
async fn main() {
    logger_config()
        .with_name("main")
        .scope_global(async move {
            log::info!("Hello, world from main thread!");
            for i in 0..5 {
                tokio::spawn(async move {
                    logger_config()
                        .with_name(&format!("thread {i}"))
                        .scope_local(async move {
                            log::warn!("Hello, world from thread {i}!")
                        }).await;        
                });
            }
            tokio::time::sleep(std::time::Duration::from_millis(1)).await; // wait for log to flush
        }).await;
}

Logging to files

Files can be used to log messages. The log file is created if it does not exist and appended to if it does. Threads can log to different files. If no file is specified in local config, the global file is used.

use mtlog_tokio::logger_config;

#[tokio::main]
async fn main() {
    logger_config()
        .with_log_file("/tmp/app.log")
        .unwrap()
        .no_stdout() // disable stdout logging if needed
        .scope_global(async move {
            log::info!("Hello, world!");
            tokio::time::sleep(std::time::Duration::from_millis(1)).await; // wait for log to flush
        }).await;
    assert!(std::fs::read_to_string("/tmp/app.log").unwrap().ends_with("Hello, world!\n"));
}

Dependencies

~3–11MB
~113K SLoC