Structured logs and tracing
Quick answer
Structured logs describe an event with named fields, while traces connect operations across a request using spans and context. They help diagnose failures without searching arbitrary prose.
Choose meaningful fields
Use stable event names, severity, duration and a correlation identifier when appropriate. Keep passwords, tokens and sensitive payloads out of logs. Production code can use tracing spans and a configured subscriber; these examples model the event fields without requiring a logging crate. Avoid arbitrary user text in raw log lines and use a real serializer for machine-readable formats.
fn main() { let request_id = 17u64; let status = 200u16; println!("event=request_done request_id={request_id} status={status}");}Expected stdout (not executed):
event=request_done request_id=17 status=200Only selected numeric fields and a fixed event name are logged.
fn lookup(request_id: u64) { println!("event=lookup request_id={request_id}"); }fn main() { lookup(5); println!("event=reply request_id=5"); }Expected stdout (not executed):
event=lookup request_id=5event=reply request_id=5The shared ID correlates the operations; it is not a complete distributed trace.
Common mistake
Do not log raw authorization headers or full request bodies by default.
Try it yourself
Add a fixed failure event and choose fields that help identify the cause without exposing credentials.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Structured logs and tracing — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A request log includes arbitrary Authorization headers. What should be changed?
Structured logs and tracing — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let request_id = 17u64; let status = 200u16; println!("event=request_done request_id={request_id} status={status}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Structured logs and tracing — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn lookup(request_id: u64) { println!("event=lookup request_id={request_id}"); } fn main() { lookup(5); println!("event=reply request_id=5"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.