Adding a appender to log4rs at runtime

Hello

I'm a noob to rust, i'm writing a program that logs to syslog and optionally (if the user pass a parameter) logs to the console.

This is how the logger is configured

let stdout = ConsoleAppender::builder().build();
let syslog = Box::new(
    log4rs_syslog::SyslogAppender::builder()
    .openlog("cronrunner", log4rs_syslog::LogOption::LOG_PID,log4rs_syslog::Facility::Daemon)
    .build(),
);
let config = Config::builder()
    .appender(Appender::builder().build("stdout", Box::new(stdout)))
    .appender(log4rs::config::Appender::builder().build(
        "syslog",
        syslog,
    ))
    .logger(Logger::builder()
        .appender("syslog")
        //.appender("stdout")
        .additive(false)
        .build("cronrunner", LevelFilter::Info))
    .build(Root::builder().appender("stdout").build(LevelFilter::Info))
    .unwrap();

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

If I uncomment .appender("stdout") I get logs to both syslog and the console :slight_smile: , how can I make this dynamically depending on a parameter passed to the program?

Also I'd like to change the LevelFilter at runtime, how can I do that? (just passing a String with the LevelFilter to build() does not work

Should be as simple as this:

let mut builder = Logger::builder().appender("syslog");
if should_log_to_console {
    builder = builder.appender("stdout");
}
builder.additive(false).build("cronrunner", LevelFilter::Info)

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.