Turn off tracing at compile time for specific crate

I am writing a high performance library and want to use the tracing crate for debugging purposes. I am emitting very verbose trace information and would like consumers of the library to not pay the cost of that. I know there's the max_level_* features, but I think those would apply to all crates pulled in by the binary then. Can I disable tracing at compile time for just a specific crate?

I'm doing this on a phone and off the top of my head so a couple of typos may creep in, but:

Not that I know of. But what you could do is wrap all the tracing macros in versions from your won crate:

macro_rules! info {
    ($fmt:expr $(, $args:expr)* ) => {
        if cfg!(feature = "tracing") {
            log::info!($fmt $(, $args)*):
        }
    } 
} 

// similar for error, debug, trace etc

You may have to update the accepted pattern if you want to use named keys; otherwise this version will do fine.

And then add this to your Cargo.toml:

[features]
tracing = ["log"]

After that all you need to do is update the call sites of your info! macro (and analogs for error, debug etc) to refer to this one version.
The "tracing" compile time feature flag must then be provided for tracing to take effect (e.g. cargo build --features tracing); otherwise the macro compiles to a NOP, and thus consumes 0 resources at runtime.

1 Like

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.