home
NOTE: Under Construction - I'm in the middle of upgrading my site and lots of stuff is kinda broken. Please forgive the mess.

Create JSON Log Files In Rust With tracing

April 2024

This is what I'm using for my default logs to produce JSON output in Rust apps.

Code
```cargo
[dependencies]
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["json"] }
```
use tracing::{Level, event, instrument};

#[instrument]
fn main() {
    let format = tracing_subscriber::fmt::format()
      .json();
    tracing_subscriber::fmt()
      .event_format(format)
      .with_max_level(Level::DEBUG)
      .init();
  event!(Level::INFO, "This is the log message");
  event!(Level::DEBUG, "This is a debug message");
}
Results
{"timestamp":"2024-04-23T14:42:04.834323Z","level":"INFO","fields":{"message":"This is the log message"},"target":"_active_nvim_run"}
{"timestamp":"2024-04-23T14:42:04.834498Z","level":"DEBUG","fields":{"message":"This is a debug message"},"target":"_active_nvim_run"}

Details

  • The biggest thing to note is that in order to use the `.json()rust call, you have to add the "feature" in Cargo.toml

═══ § ═══

Footnotes And References