Eyal leshem
Eyal leshem

Reputation: 1115

How do I change the log level of a running process with log4rs?

I am trying to change log-level dynamically during the run of my Rust program.

I used log4rs as in their example they claimed it's possible.

But when I run the following program it crashes - when I try to change the log level - and I think it's a restriction of the log API (according to that: https://github.com/rust-lang/log/blob/master/src/lib.rs#L1278)

Is there anyway other way that I could change the log-level in runtime?

Here is what I am trying to do:

use log4rs::append::console::ConsoleAppender;
use log4rs::append::console::Target;
use log4rs::config::{Appender, Config, Root}; 

use log::*;

fn main() {
    let level_info = log::LevelFilter::Info; 
    let level_trace = log::LevelFilter::Trace;


    let stderr = ConsoleAppender::builder().target(Target::Stderr).build();
    let config = Config::builder().appender(
        Appender::builder()
            .build("stderr", Box::new(stderr)),
    ).build(
        Root::builder()
            .appender("stderr")
            .build(level_info),
    ).unwrap();

    log4rs::init_config(config).unwrap(); 


    error!("error"); //should print 
    warn!("warn");   //should print
    info!("info");   //should print
    debug!("debug"); //should  not print
    trace!("trace"); //should  not print 


    let stderr = ConsoleAppender::builder().target(Target::Stderr).build();
    let config = Config::builder().appender(
        Appender::builder()
            .build("stderr", Box::new(stderr)),
    ).build(
        Root::builder()
            .appender("stderr")
            .build(level_trace),
    ).unwrap();

    log4rs::init_config(config).unwrap(); 


    error!("error2"); //should print
    warn!("warn2");   //should print
    info!("info2");   //should print
    debug!("debug2"); //should print
    trace!("trace2"); //should print  

}

The output:

2020-04-20T12:07:53.351080400+01:00 ERROR use_log4rs - error
2020-04-20T12:07:53.354078400+01:00 WARN use_log4rs - warn
2020-04-20T12:07:53.356077200+01:00 INFO use_log4rs - info
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: SetLoggerError(())', src\main.rs:48:5

Upvotes: 5

Views: 2172

Answers (2)

Daniel del Castillo
Daniel del Castillo

Reputation: 21

Jmb's answer is correct, but to change the log level of a process you don't need to change the config. log4rs relies on log, so you can just use log::set_max_level, which doesn't need a handle.

log::set_max_level(LevelFilter::Warn);

Just make sure you aren't filtering anything in the log4rs side.

Example

Upvotes: 2

Jmb
Jmb

Reputation: 23339

You can only call init_config once. However, it returns a handle with a set_config method, which you can call to change the configuration afterwards:

let hndl = log4rs::init_config(config).unwrap();

// ...
// Apply new config:
hndl.set_config(config);

Playground

Upvotes: 5

Related Questions