Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use *simplelog* instead of *env_logger* #41

Open
KyrietS opened this issue Dec 16, 2021 · 0 comments
Open

Use *simplelog* instead of *env_logger* #41

KyrietS opened this issue Dec 16, 2021 · 0 comments
Labels
improvement Code refactor or minor changes that are not new features

Comments

@KyrietS
Copy link
Owner

KyrietS commented Dec 16, 2021

env_logger doesn't support redirecting the output to custom pipe. They have Target but it's broken for a year now and they doesn't seem to care much about it.

simplelog is able to redirect the messages to custom pipes. This would allow me to capture logs in integration tests (not sute if it's a good idea yet). I would be also easier to redirect logs to the file.

Example

This example shows combined logger where ERROR and WARN messages are printed to the console with colors while INFO, WARN and ERROR messages are additionaly captured and stored in a channel waiting to be extracted later.

// [dependencies]
// log = "0.4.0"
// simplelog = "0.11.1"

#[macro_use]
extern crate log;
extern crate simplelog;

use simplelog::*;

use std::{
    io,
    sync::mpsc::{channel, Sender},
};

struct WriteAdapter {
    sender: Sender<u8>,
}

impl io::Write for WriteAdapter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        for chr in buf {
            self.sender.send(*chr).unwrap();
        }
        Ok(buf.len())
    }

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

fn setup_logger() -> std::sync::mpsc::Receiver<u8> {
    let (rx, tx) = channel();
    let my_adapter = WriteAdapter { sender: rx };

    CombinedLogger::init(
        vec![
            TermLogger::new(LevelFilter::Warn, Config::default(), TerminalMode::Mixed, ColorChoice::Auto),
            WriteLogger::new(LevelFilter::Info, Config::default(), my_adapter),
        ]
    ).unwrap();

    return tx;
}

fn main() {
    let tx = setup_logger();

    trace!("some trace log");       // won't be printed
    debug!("some debug log");       // won't be printed
    info!("some information log");  // from pipe
    warn!("some warning log");      // console & from pipe
    error!("some error log");       // console & from pipe

    // Collect all messages send to the channel and parse the result as a string
    String::from_utf8(tx.try_iter().collect::<Vec<u8>>())
        .unwrap()
        // Split the result into lines so a prefix can be added to each line
        .split('\n')
        .for_each(|msg| {
            // Print the message with a prefix if it has any content
            if !msg.is_empty() {
                println!("from pipe: {}", msg)
            }
        });
}
@KyrietS KyrietS added the improvement Code refactor or minor changes that are not new features label Dec 16, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
improvement Code refactor or minor changes that are not new features
Projects
None yet
Development

No branches or pull requests

1 participant