Drakulix / simplelog.rs

Simple Logging Facility for Rust
https://docs.rs/simplelog/
Apache License 2.0
414 stars 71 forks source link

Multiple, intependen logger #154

Closed jb-alvarado closed 2 months ago

jb-alvarado commented 2 months ago

Hello, I would like to ask if somebody can give me some hints/examples of how to create multiple independent loggers.

Using CombinedLogger with TermLogger, LogMailer and different Levels is not enough. Both loggers needs to have all levels.

I try something like this:

use log::{LevelFilter, Log, Metadata, Record};
use simplelog::*;
use std::fs::File;

struct Log2 {
    logger: Box<WriteLogger<File>>,
}

impl Log2 {
    fn new() -> Self {
        let log_file = File::create("log_file.log").expect("Failed to create log file");

        let config = ConfigBuilder::new()
            .set_time_format_custom(format_description!(
                "[[[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:5]]"
            ))
            .build();

        let logger = WriteLogger::new(LevelFilter::Debug, config, log_file);

        Log2 { logger }
    }

    fn debug(&self, message: &str) {
        self.logger.log(
            &Record::builder()
                .args(format_args!("{}", message))
                .level(Level::Debug)
                .build(),
        );
    }
}

fn main() {
    TermLogger::init(
        LevelFilter::Debug,
        Config::default(),
        TerminalMode::Mixed,
        ColorChoice::Auto,
    )
    .unwrap();

    let log2 = Log2::new();

    log2.debug("Debug-Message in Logger 2");

    info!("Info in Logger 1");
    warn!("Warning in Logger 1");
}

But the problem with that is, that I can not clone Log2 and send it to different threads. It also override the log file after every restart.

Using for both logger the logging macros would be even more nice, but I guess that is not possible?

jb-alvarado commented 2 months ago

I saw now that the log crate have a target: command. flexi_logger uses this to redirect to different logger: https://docs.rs/flexi_logger/latest/flexi_logger/writers/index.html.

Something like that would be awesome in simplelog.