Search code examples
loggingenvironment-variablesrust

Is there a way to programmatically change the default logging level of the log crate?


I'm developing a project in Rust that is meant to be used by systems administrators, via CLI. In this program, I would like to have lines like these:

warn!("File {} not found, proceeding to next file", file_path);

Which I don't consider errors in the context of the software, but I still would want my users to be aware of.

However, Rust's logging system, by default, only prints messages on the ERROR log level, and the only way I found to change this default is to set the RUST_LOG environment variable - which I don't want my users to have to do. I guess I could create a wrapper script that just sets the variable and execs the program, but I would rather not.

Is there a way to change the default level programmatically, from inside the program?


Solution

  • No, this is not possible. Just skimming through the code of liblog library you can see that all log level configuration is stored in global variables which are modified only once, using Once primitive, and there is no way to modify this configuration.

    Rust logging is very simple; if you want something more sophisticated, you will have to do it yourself. liblog provides an extension point, a trait called Logger, it probably can be used for your purpose.