log
log copied to clipboard
Can we set log filter level at runtime
Hi, I read the docs and find that the log filter level can only be set at complie time, I tested the set_max_level()
function, can only find the max_level changed, but the filter still remain as the original setup.
Here is my test code
fn main() {
let mut logger = env_logger::Builder::new();
logger.format(|buf, record| {
writeln!(
buf,
"[{}] {} {}:{} - {}",
record.level(),
chrono::Local::now().format("%Y-%m-%dT%H:%M:%S.%3f"),
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.args()
)
})
.filter(None, log::LevelFilter::Info);
logger.init();
println!("current max log level is : {:?}", log::max_level());
log::trace!("this is a trace log");
log::debug!("this is a debug log");
log::info!("this is a info log");
log::warn!("this is a warn log");
log::error!("this is a error log");
// logger.filter(None, log::LevelFilter::Debug);
log::set_max_level(log::LevelFilter::Debug);
sleep(Duration::from_secs(3));
println!("current max log level is : {:?}", log::max_level());
log::trace!("this is a trace log");
log::debug!("this is a debug log");
log::info!("this is a info log");
log::warn!("this is a warn log");
log::error!("this is a error log");
}
So my issue is, is it possible to change the log filter at runtime? I have met such situation in my development work. Thank you.
You can use set_max_level
to change the log level at runtime.
You can use
set_max_level
to change the log level at runtime.
@Thomasdezeeuw Hi, I ran the test code above, the max_level did changed, but the filter remains the same, here is the output
there should be a line like "[DEBUG] YYYY-MM-DD - this is a debug log", but there wasn't, which means
set_max_level()
only changed a static variable but filter didn't change.
Have you set either the max_level_*
or release_max_level_*
features? Because those can't be lowered as they remove all the logs at compile time. For example setting the max_level_warn
feature removes all trace, debug and info logs.
If not it might depend on the env_logger crate, e.g. try using env_logger::Builder::filter_level
.
For example setting the
max_level_warn
feature removes all trace, debug and info logs.
yes, that's correct, I changed the filter level at compile time, then the runtime level can alter as I need. Thank you!