tracing-bunyan-formatter icon indicating copy to clipboard operation
tracing-bunyan-formatter copied to clipboard

How to include request span trace id in log?

Open npuichigo opened this issue 2 years ago • 2 comments

I use axum and opentelemetry, currently I include the trace id in response header with middleware's help. But how can I also include that trace id in the output of this formatter?

The trace id in response header can be used with Jaeger for searching, but I would like to locate in logs as well.

sample code use opentelemetry: https://github.com/AmineDiro/cria/blob/5b80514171930725bfb57212f37243e16c4394ba/src/lib.rs#L95

npuichigo avatar Nov 01 '23 13:11 npuichigo

This formatter outputs whatever is attached to the span—there's no special work or setup you need to do here. If the field is correctly attached to a span, it'll show up in the output.

LukeMathWalker avatar Nov 02 '23 08:11 LukeMathWalker

Thanks. I used tower-http middleware to include both request/respond headers to attach to a span and it works now to show both request_id added as x-request-id and trace_id added by opentelemetry.

let svc = ServiceBuilder::new()
    // make sure to set request ids before the request reaches `TraceLayer`
    .set_x_request_id(MyMakeRequestId::default())
    // log requests and responses
    .layer(
        TraceLayer::new_for_http()
            .make_span_with(DefaultMakeSpan::new().include_headers(true))
            .on_response(DefaultOnResponse::new().include_headers(true))
    )
    // propagate the header to the response before the response reaches `TraceLayer`
    .propagate_x_request_id()
    .service(handler);

npuichigo avatar Nov 02 '23 09:11 npuichigo