rust-cli / env_logger

A logging implementation for `log` which is configured via an environment variable.
https://docs.rs/env_logger
Apache License 2.0
826 stars 128 forks source link

How to use env_logger with several libs? #131

Closed clearloop closed 5 years ago

clearloop commented 5 years ago

_Using acitx-web in my latest app, the logger middleware which has already implemented env_logger._

How to print logs outside the actix_web lib?

In env_logger's doc, we can enable all logs like this, but it seems not work for the following scene:

#[macro_use]
extern crate log;
use actix_web::{middleware, App};

fn main() -> std::io::Result<()> {
    std::env::set_var("RUST_LOG", "actix_web=main");
    // std::env::set_var("RUST_LOG", "main");
    // this can print app's log, but actix_web`s ignored.
    env_logger::init();

    // -*- how to print out this? -*-
    info!("this will not print out....");

    let app = || App::new()
        .wrap(middleware::Logger::new("%r %s"))
        //...
}

Note: actix-web's Logger middleware just refs questions to env_logger....

KodrAus commented 5 years ago

Hi @clearloop :wave:

What you're looking at there are module-level filters. If you specify just a minimum level then env_logger will output log records from anywhere that match that level.

Give this a try:

#[macro_use]
extern crate log;
use actix_web::{middleware, App};

fn main() -> std::io::Result<()> {
    // Init using RUST_LOG, or all info level events if the env var is not set
    // The string given to default_filter_or is the same format as the env var
    env_logger::init_from_env(env_logger::Env::default().default_filter_or("info"));

    info!("this should now print out");

    let app = || App::new()
        .wrap(middleware::Logger::new("%r %s"))
        //...
}
clearloop commented 5 years ago

What you're looking at there are module-level filters. If you specify just a minimum level then env_logger will output log records from anywhere that match that level.

Wow, it works!! thank you very much!!