How to pass the log4rs to sub module

Hello,

I am pretty new to use log4rs (even rust to be honest) and don't know the best way to pass the logger to submodule.

I have successfully done the conf. at the main level (and log work) but I don't know how to pass it to module (do I need to pass it as a reference or using lazy_static. Getting confuse at this point and I don't find some proper example.

Thanks in advance,

Jean-Philippe

I haven't used that logging crate, but most logging crates install themselves in a global somewhere and allow you to use info!, warn! and friends as if they were println!.

1 Like

When you init log4rs, it'll register itself with the log crate as the global logger. You can then use the macros provided by log (info!, warn!, etc. as mentioned by @alice) anywhere in your crate.

log4rs (and most other loggers) use log like this because it allows a shared interface for all binaries and libraries. If any library you use depends on log as well, it can get access to the set global logger without having to be configured manually, or having to depend on any specific logging backend (like log4rs).

Thanks, it works perfectly.

I have another question related to the log4rs. How can I use the logger to redirect both stderr & stdout to the log4rs ?

Thanks in advance for your precious help,

This example comes from main rust documentation (https://rust-lang-nursery.github.io/rust-cookbook/os/external.html)

use std::fs::File;
use std::io::Error;
use std::process::{Command, Stdio};

fn main() -> Result<(), Error> {
let outputs = File::create("out.txt")?;
let errors = outputs.try_clone()?;

Command::new("ls")
    .args(&[".", "oops"])
    .stdout(Stdio::from(outputs))
    .stderr(Stdio::from(errors))
    .spawn()?
    .wait_with_output()?;

Ok(())

}

In order to post code blocks, you surround them with triple backtics:

```
// your code
```

As for your question, you would have to intercept it with a pipe and manually print it to log4rs.

thanks I will try that

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.