how can I ignore certain attributes based on feature flag (without cfg_attr)?

156 Views Asked by At

My crate has a "tracing" feature. When it's turned on, I include dependencies tracing, tracing_subscriber, etc. When it's turned off, those dependencies are also turned off, which means that uses of functions/macros/attributes from those crates won't compile.

For functions and macros, I can conditionally define stub versions to make these no-ops, e.g.

    macro_rules! info {
        ($($arg:tt)*) => {};
    }
    pub(crate) use info;

Is it possible to do the same for attributes, in particular the instrument attribute? I don't want to have to rewrite all the callsites to use cfg_attr, I'd rather handle toggling the behavior in one place.

bonus question: is this a reasonable approach for this type of situation? I expect I'm not the first to want to do something like this.

1

There are 1 best solutions below

0
Hugo Mota On

As stated in the comments, the documentation for tracing states that libraries should only rely on tracing and leave the actual consuming of data to the applications.

Libraries should only rely on the tracing crate and use the provided macros and types to collect whatever information might be useful to downstream consumers.

Since you're trying to get rid of the instrumentation calls, you're probably worried about overhead. Documentation states that:

For performance reasons, if no currently active collectors express interest in a given set of metadata by returning true, then the corresponding Span or Event will never be constructed.

The compiler is also keen at getting rid of things that you never use. There's a good chance the overhead you're trying to get rid of is zero. Of course, to be sure you would need to run benchmarks or to inspect the assembly code.

The Tokio project is the maintainer of this crate, so you can also join their Discord server and ask the community about it.