Skip to content

How to separate logs by thread? #3137

Answered by kaffarell
Kakapio asked this question in Q&A
Discussion options

You must be logged in to vote

You could just create a custom Layer (https://docs.rs/tracing-subscriber/latest/tracing_subscriber/layer/index.html) and then check a task_local storage (https://docs.rs/tokio/latest/tokio/macro.task_local.html) in the on_event function. e.g. something like this:

struct CustomSubscriber {}

impl<S: Subscriber> Layer<S> for CustomSubscriber {
    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
        LOG.with(|flag| {
            if *flag {
                // log
            }
        })
    }
}

fn main() {
    tracing_subscriber::registry()
        .with(CustomSubscriber {})
        .init();

    let _ = std::thread::spawn(|| {
        LOG.sync_scope(true, || {

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@QnnOkabayashi
Comment options

@Kakapio
Comment options

Answer selected by Kakapio
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants