home ~ projects ~ socials

Create JSON Log Files In Rust With tracing

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

```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");
}
Output:
{"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
-- end of line --

References