0

In my Rust Rocket REST application I use env_logger for logging, which I've configured with something similar to this:

env_logger::builder()
    .format(|buf, record| {
        writeln!(buf, "{}: {}", record.level(), record.args())
    })
    .init();

If most of the requests I expect contain a user/session identifier inside a header or inside the JSON POST request data (under a well-known name), how can I do so that that user/session identifier is automatically written in all log lines where possible?

Something like:

writeln!(buf, "{} ({}): {}", record.level(), my_user_or_session_identifier, record.args())

I've done stuff like that in other languages, where I've used a request filter that adds the user/session identifier in a thread-local object at the beginning of every request.

at54321
  • 8,726
  • 26
  • 46
  • I believe the Rocket way to do it would be to make a [request guard](https://rocket.rs/v0.5-rc/guide/requests/#request-guards). – kmdreko Sep 16 '21 at 16:11
  • @kmdreko I would guess so, I also looked at (Request-Local State)[https://rocket.rs/v0.5-rc/guide/state/]. But how do I access that data from the logger's `format()` function? – at54321 Sep 16 '21 at 20:45
  • You might want to look at the [`tracing`](https://docs.rs/tracing/0.1.27/tracing/index.html) crate (I've never used it, but it looks like it could help) – Jmb Sep 17 '21 at 07:56

0 Answers0