Initialize the tracing crate with a subscriber to log structured events as key-value pairs in Rust.
Add the tracing crate to your dependencies and initialize a subscriber in main to capture structured logs.
use tracing::{info, Level};
use tracing_subscriber;
fn main() {
tracing_subscriber::fmt()
.with_max_level(Level::INFO)
.init();
info!(user_id = 42, "User logged in");
}
Add this to Cargo.toml:
[dependencies]
tracing = "0.1"
tracing-subscriber = "0.3"
Structured logging records events as key-value pairs instead of plain text, making it easier for computers to search and analyze your logs. It matters because it lets you filter logs by specific data points, like user IDs, without writing complex parsing scripts. Think of it as filling out a standardized form for every event instead of writing a free-form sentence.