Fred Hors
Fred Hors

Reputation: 4116

How to conditionally call tracing-subscriber methods?

I'm trying to setup tracing and I have this code but it compiles with errors:

use tracing_subscriber;

pub fn init(is_pretty: bool) {
    let subscriber = tracing_subscriber::fmt();
    if is_pretty {
        &subscriber.pretty();
    }
    subscriber.init();
}
error[E0382]: use of moved value: `subscriber`
   --> src\main.rs:8:5
    |
4   |     let subscriber = tracing_subscriber::fmt();
    |         ---------- move occurs because `subscriber` has type `SubscriberBuilder`, which does not implement the `Copy` trait
5   |     if is_pretty {
6   |         &subscriber.pretty();
    |                     -------- `subscriber` moved due to this method call
7   |     }
8   |     subscriber.init();
    |     ^^^^^^^^^^ value used here after move

I tried this too but I get different compiler errors:

use tracing_subscriber;

pub fn init(is_pretty: bool) {
    let mut subscriber = tracing_subscriber::fmt();
    if is_pretty {
        subscriber = subscriber.pretty();
    }
    subscriber.init();
}
error[E0308]: mismatched types
 --> src\main.rs:6:22
  |
4 |     let mut subscriber = tracing_subscriber::fmt();
  |                          ------------------------- expected due to this value
5 |     if is_pretty {
6 |         subscriber = subscriber.pretty();
  |                      ^^^^^^^^^^^^^^^^^^^ expected struct `DefaultFields`, found struct `Pretty`
  |
  = note: expected struct `SubscriberBuilder<DefaultFields, Format<tracing_subscriber::fmt::format::Full>>`
             found struct `SubscriberBuilder<Pretty, Format<Pretty>>`

How can I fix this?

Upvotes: 1

Views: 629

Answers (1)

jthulhu
jthulhu

Reputation: 8667

SubscriberBuilder encodes in its type the various options used to build the subscriber, so the only way to go would be:

if is_pretty {
    tracing_subscriber::fmt()
        .with_env_filter("info")
        .pretty()
        .init();
} else {
    tracing_subscriber::fmt()
        .with_env_filter("info")
        .init();
}

The fact is that this builder was probably thought to have "hard-coded" configuration.

Upvotes: 3

Related Questions