How to conditionally use tracing's non_blocking writer instead of stdout?

469 views Asked by At

I'm using the below code to initialize my tracing subscriber. I would like to use the non_blocking writer only in some cases else I need to use simply the stdout one.

How can I avoid the below error?

use tracing_appender::non_blocking;
use tracing_log::LogTracer;
use tracing_subscriber::{fmt::Layer, prelude::*, EnvFilter, Registry};

pub fn init(tracing: &Tracing) -> non_blocking::WorkerGuard {
    LogTracer::init().expect("init LogTracer");

    let (non_blocking, non_blocking_guard) = non_blocking(std::io::stdout());

    let base_layer;

    if tracing.blocking {
        base_layer = Layer::default().with_writer(std::io::stdout);
    } else {
        base_layer = Layer::default().with_writer(non_blocking);
    }

    let mut layers = Vec::new();

    layers.push(if tracing.pretty {
        base_layer.pretty().with_file(false).boxed()
    } else {
        base_layer.json().boxed()
    });

    let registry = Registry::default()
        .with(EnvFilter::from(&tracing.level))
        .with(layers);

    tracing::subscriber::set_global_default(registry).unwrap();

    non_blocking_guard
}
error[E0308]: mismatched types
    |
18  |         base_layer = Layer::default().with_writer(non_blocking);
    |                                       ----------- ^^^^^^^^^^^^ expected fn item, found struct `tracing_appender::non_blocking::NonBlocking`
    |                                       |
    |                                       arguments to this function are incorrect
    |
    = note: expected fn item `fn() -> std::io::Stdout {std::io::stdout}`
                found struct `tracing_appender::non_blocking::NonBlocking`
note: associated function defined here
    |
177 |     pub fn with_writer<W2>(self, make_writer: W2) -> Layer<S, N, E, W2>
    |            ^^^^^^^^^^^
1

There are 1 answers

0
kmdreko On BEST ANSWER

You can use BoxMakeWriter to type-erase the concrete type of the writer in order to unify them for later. I would initialize your tracing like so:

use tracing_subscriber::fmt::writer::BoxMakeWriter;

let writer = if tracing.blocking {
    BoxMakeWriter::new(std::io::stdout)
} else {
    BoxMakeWriter::new(non_blocking)
};

let layer = if tracing.pretty {
    Layer::default()
        .with_writer(writer)
        .pretty()
        .with_file(false)
        .boxed()
} else {
    Layer::default()
        .with_writer(writer)
        .json()
        .boxed()
};

let registry = Registry::default()
    .with(EnvFilter::from(&tracing.level))
    .with(layer);

Note: you didn't need to create a vector of layers; the result of .boxed() can be used directly.