Skip to content

enabled() methods don't respect the target filter #144

@ajenkinski

Description

@ajenkinski

The log_enabled! macro supports a target keyword, to check if logging is enabled with for a given target. The documentation gives this example for instance:

if log_enabled!(target: "Global", Debug) {
   let data = expensive_call();
   debug!(target: "Global", "expensive debug data: {} {}", data.x, data.y);
}

However, the above example would not work correctly when using simplelog as the logging implementation, because simplelogging's implementations of the enabled() method, which log_enabled! depends on, only checks the level, but not the target. So in the above example, if the "Global" target was being filtered out, but the current level was Debug, then the body of the if-statement would still execute. Note, the log! macros themselves do correctly filter on target in addition to level.

Reproduction:

use log::{debug, log_enabled, Level};
use simplelog::{ConfigBuilder, LevelFilter, SimpleLogger};

fn main() {
    SimpleLogger::init(
        LevelFilter::Debug,
        ConfigBuilder::new()
            .add_filter_allow_str("foo")
            .build(),
    )
    .unwrap();

    if log_enabled!(target: "bar", Level::Debug) {
        println!("This shouldn't be printed because only target `foo` is enabled, but it will be printed");
        debug!(target: "bar", "This will be correctly filtered out and won't print");
    }
}

The expected behavior is that the whole if-block body would be skipped, but in fact the body is executed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions