emabee / flexi_logger

A flexible logger for rust programs that can write to stderr, stdout, and/or to log files
Apache License 2.0
314 stars 55 forks source link

Custom logging level #166

Closed konqueror1 closed 4 months ago

konqueror1 commented 4 months ago

I am using flexy_logger for simultaneously log to file and stdout. I try using that macro:

macro_rules! bold_red { ($($arg:tt)) => ( log::log!(log::Level::Info, "{}", format_args!("\x1b[1;31m{}\x1b[0m", format_args!($($arg))) ); ) }

Stdout works perfect but when writing to file ANSI escape codes are in the file. I can strip codes with regex as workaround but I am sure there is more idiomatic way to do it.

emabee commented 4 months ago

Yes, you can achieve what you need with something like this:

use flexi_logger::{Duplicate, FileSpec, Logger};
use log::{debug, error, info, trace, warn};

fn main() {
    let _logger = Logger::try_with_env_or_str("info")
        .unwrap()
        .log_to_file(FileSpec::default())
        .duplicate_to_stdout(Duplicate::All)
        .start()
        .unwrap();

    error!("Test error");
    warn!("Test warning");
    info!("Test info");
    debug!("Test debug");
    trace!("Test trace");
}

The program prints to stdout in colors and writes to the file without color escape codes.