0

Having trace_id field on all log events is common practice in distributed applications. This enables us to be able to follow logs for a specific request in the application.

I have an actix-web middleware that extracts a header from the http requests (X-Amzn-Trace-Id: Root=1-63441c4a-abcdef012345678912345678) and sets the string content to a tokio tracing span field called trace_id.

I can't figure out a way to have this field on all log events.

Potential approaches:

  • Use request extensions and pass trace_id as a function parameter down (doesn't seem clean)
  • log all spans in the spans array field (inefficient as you will log a lot of duplicate data as all the child spans will have parent spans logged)
  • somehow propagate trace_id field to all child spans, this way we can only log the current span and have trace_id field as well.
Farhad Farahi
  • 35,528
  • 7
  • 73
  • 70
  • Anecdotally, you would use *opentelemetry* for distributed tracing (though with a *tracing* facade if you prefer) which would communicate any trace ids to your log/trace ingester of choice. So this might not be needed at all. However, I *have* needed this before to explicitly have a trace and span ids directly on each log message; I resorted to wrapping the tracing macros in my own macro which would pull those ids from the current opentelemetry context and pass them as log attributes. – kmdreko Jun 27 '23 at 23:58
  • Hard to answer without more details about your `tracing` setup, but this can be accomplished with a custom formatter that loops through the spans array to find one that has the `trace_id` field. See [`tracing_subscriber::fmt::FormatEvent`](https://docs.rs/tracing-subscriber/0.3.17/tracing_subscriber/fmt/trait.FormatEvent.html) for an example of how to make a custom formatter. – Jmb Jun 28 '23 at 06:49
  • @kmdreko opentelemetry trace_id has a specific format, I dont think that i can set the string posted above(aws loadbalancer traceid) in – Farhad Farahi Jun 28 '23 at 16:47
  • @FarhadFarahi oh right, I glossed over that. – kmdreko Jun 28 '23 at 17:37

0 Answers0