Use the tracing crate with the tracing-subscriber JSON layer to output logs as structured JSON. Add tracing and tracing-subscriber to your Cargo.toml, then initialize the subscriber in main before logging.
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, fmt::Layer};
fn main() {
let json_layer = Layer::new()
.json()
.with_target(false)
.with_thread_ids(false)
.with_thread_names(false)
.with_file(false)
.with_line_number(false);
tracing_subscriber::registry()
.with(tracing_subscriber::filter::LevelFilter::INFO)
.with(json_layer)
.init();
tracing::info!(message = "Application started", user_id = 123);
}
Add this to your Cargo.toml:
[dependencies]
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["json"] }
Run your application to see JSON-formatted logs like:
{"message":"Application started","user_id":123}