Enabling Tracing Logging for a Specific Module

tracing alone isn't emitting any log messages without a Subscriber that determines how the log messages should be displayed. The common choice of implementation can be found in the tracing-subscriber crate. Here is how you can use tracing-subscriber to restrict log-messages printed in stdout to a specific module:

/*
[dependencies]
tracing = "*"
tracing-subscriber = { version = "^0.3.16", features = ["env-filter"] }
*/
mod foo {
    pub fn hello_logger() {
        tracing::info!("hello from foo");
    }
}

mod bar {
    pub fn hello_logger() {
        tracing::info!("hello from bar");
    }
}


fn main() {
    tracing_subscriber::fmt()
        .with_env_filter("playground::foo=info")
        .init();

    foo::hello_logger();
    bar::hello_logger();
}

Rustexplorer

Stdout:

2023-03-01T10:30:20.000992Z  INFO playground::foo: hello from foo

Only the log messages from the foo module are printed.

You can read more about configuring your subscriber to log certain things and not others here or here and basically all through the tracing-subscriber docs.

1 Like