The tracing crate
Learn what the tracing crate is, how its events and levels work, and how to add the first structured log lines to a Rust program
The tracing crate is the standard way for a Rust program to describe what it is doing while it runs. It gives your code a set of macros, such as tracing::info! and tracing::error!, that record structured diagnostic information. Structured means each log line carries named pieces of data, such as a user id or an order id, instead of hiding those facts inside a plain sentence.
Where This Fits
A server that handles one request at a time can get by with plain printed lines. A server that handles many requests at once cannot, because the printed lines from different requests mix together and there is no way to tell which line belongs to which request. The tracing crate exists to solve that problem at the source, by recording what happened together with the facts that identify the work it belonged to. This page covers the crate itself and its most basic building block, the event. The ideas of spans, which group events into units of work, and subscribers, which decide what happens to the recorded data, get their full treatment on their own pages.
Think of a hospital reception desk. A plain log is a notebook where the receptionist writes "patient seen" again and again, with no name attached. A structured log is the same notebook with a name, a time, and a department written on every line. The second notebook takes no more effort to write, but it is the only one that lets anyone find what happened to one particular patient later.
The Smallest Working Version
A program that uses tracing needs three things, in this order: the crates in Cargo.toml, one line that switches output on, and a macro call that records something. Each step depends on the one before it, so follow them in order.
Step 1: Add the dependencies
Open Cargo.toml and add tracing and tracing-subscriber to the dependencies:
[package]
name = "trace_first_steps"
version = "0.1.0"
edition = "2021"
[dependencies]
tracing = "0.1"
tracing-subscriber = "0.3"
The tracing crate provides the macros your code calls, such as tracing::info!. The tracing-subscriber crate provides the piece that prints those calls to the terminal. The two crates are separate on purpose: tracing only records diagnostic data, and a subscriber decides what to do with it. The versions shown here are the current ones, tracing 0.1.44 and tracing-subscriber 0.3.23, and the "0.1" and "0.3" requirements accept those releases.
Step 2: Switch output on
At the very start of main, before any macro call that should be seen, add this line:
tracing_subscriber::fmt().init();
This installs a subscriber that formats events as readable text and prints them to the terminal. Without this line, every tracing::info! call in the program runs and produces nothing, with no error and no warning. That silence is the most common surprise for beginners, and it is covered in detail below.
Step 3: Record an event
Add an event macro call after the subscriber line:
tracing::info!("server started");
An event is a single thing that happened at a single moment, written down with a level and a message. The info! macro records an event at the INFO level, which marks routine information the operator wants to see under normal conditions.
Step 4: Run the program
Run the program with cargo run. The terminal shows the event as one line:
2026-11-14T11:47:44.287223Z INFO trace_first_steps: server started
The line starts with a timestamp, then the level INFO, then the name of the crate the event came from, then the message. The exact timestamp is different on every run. The rest of the line is the same every time.
Here is the whole program in one place, so the three pieces can be seen together:
fn main() {
tracing_subscriber::fmt().init();
tracing::info!("server started");
}
[package]
name = "trace_first_steps"
version = "0.1.0"
edition = "2021"
[dependencies]
tracing = "0.1"
tracing-subscriber = "0.3"
Run it with cargo run and the terminal prints the single INFO line shown above, then the program ends. Nothing else happens, because the program records exactly one event and then stops. That is the whole mechanism in miniature: a macro call records an event, and the subscriber prints it.
Working Setup:
If cargo run prints a line starting with a timestamp and INFO, followed by your crate name and the message, the setup works. If it prints nothing at all, the subscriber line is missing or runs after the event macro call.
The Three Pieces in Detail
Three pieces work together every time a line appears in the terminal, and each one has a different job. Mixing up their jobs is the source of most beginner confusion, so it pays to separate them clearly.
The crate records, it does not print
The tracing crate provides the macros and the types for describing diagnostic data. It does not print anything, write any file, or send any data anywhere. When code calls tracing::info!("server started"), the crate builds a small record containing the level, the message, the place in the source code where the call sits, and the name of the module it came from. Then it hands that record to whatever subscriber is active. If no subscriber is active, the record is dropped without a sound. This split is deliberate: a library can record events without deciding how its users want to see them, and an application picks the subscriber that fits how it runs.
A beginner mental model is a reporter and an editor. The tracing macros are the reporter, out in the field writing down what happened. The subscriber is the editor, who decides what gets printed and in what form. A reporter with no editor still writes the notes, but nobody ever reads them.
An event is one thing that happened
An event is the smallest unit in tracing. It represents a single moment: a server started, a user logged in, a database connection failed. An event always has a level, a message, and optionally a set of named fields. It also carries metadata the programmer never writes by hand, such as the source file and line number where the macro was called and the module path the call came from. That metadata is what appears as the crate name in the printed line.
Events are different from spans, which are the other core idea in tracing. A span covers a period of time, such as the whole handling of one request, while an event is a point inside that time. The two ideas fit together: events happen inside spans, and the span adds its context to every event recorded while it is active. Spans get their full explanation on their own page, and for this page it is enough to know that an event on its own is a single dated fact.
The subscriber decides what happens to the record
A subscriber is the component that receives events and spans and decides what to do with them. The subscriber used in the examples on this page, tracing_subscriber::fmt(), prints events as readable lines. Other subscribers write JSON, send data to a monitoring service, or store it in a file. The subscriber also decides which events are worth printing, through a maximum level. The plain fmt().init() subscriber used above prints events at INFO level and above, and hides the two more detailed levels, TRACE and DEBUG. That default is why the setup on this page works for INFO events with no extra configuration, and it is also why a DEBUG event printed with a plain subscriber never appears.
One line of setup, many choices later:
The single line tracing_subscriber::fmt().init() is enough for learning, and it is the only subscriber setup this page needs. Choosing a different output format, reading the level from an environment variable, and building a subscriber from parts are separate subjects with their own pages. Nothing in this page depends on them.
The Five Levels
Every event has a level, a measure of how urgent or detailed it is. The levels, from most verbose to most urgent, are TRACE, DEBUG, INFO, WARN, and ERROR. Each level has its own macro: tracing::trace!, tracing::debug!, tracing::info!, tracing::warn!, and tracing::error!. The order never changes, and the meaning of each level is fixed across the whole tracing ecosystem, so a level means the same thing in your code, in a library you depend on, and in middleware that logs requests.
| Level | Macro | What it is for |
|---|---|---|
| TRACE | tracing::trace! | The finest detail, such as the value of a variable on every loop iteration |
| DEBUG | tracing::debug! | Detail useful while fixing a problem, such as which branch the code took |
| INFO | tracing::info! | Routine information about normal operation, such as a server starting |
| WARN | tracing::warn! | Something unexpected that the program recovered from, such as a retry |
| ERROR | tracing::error! | Something failed, such as a database connection that could not be made |
The level system works like a volume control with five fixed positions. A subscriber with a maximum level of INFO prints INFO, WARN, and ERROR events, and drops TRACE and DEBUG events before they reach the terminal. A subscriber with a maximum of TRACE prints everything. The level is attached when the event is recorded, not when it is printed, so the same event can be hidden in one run and shown in another without changing any code.
This program records one event at each level:
fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::TRACE)
.init();
tracing::trace!("a trace level event");
tracing::debug!("a debug level event");
tracing::info!("server started");
tracing::warn!("disk space is getting low");
tracing::error!("could not connect to the database");
}
The .with_max_level(tracing::Level::TRACE) call is the only new piece. It tells the subscriber to print every level, including the two detailed ones. Without it, the plain subscriber from the first example would print only the last three lines. Run the program and the terminal shows all five lines, verified by running this exact code:
2026-11-14T11:47:44.286959Z TRACE trace_first_steps: a trace level event
2026-11-14T11:47:44.287203Z DEBUG trace_first_steps: a debug level event
2026-11-14T11:47:44.287223Z INFO trace_first_steps: server started
2026-11-14T11:47:44.287236Z WARN trace_first_steps: disk space is getting low
2026-11-14T11:47:44.287250Z ERROR trace_first_steps: could not connect to the database
Each line shows its level next to the timestamp, and the message follows the crate name. The TRACE and DEBUG lines only appear because the maximum level was raised to TRACE. Change the maximum to INFO and run again, and the first two lines vanish while the last three stay exactly the same. That experiment is worth doing once, because it makes the level system concrete: the level filters at the subscriber, and the code that records the events does not change.
Pick the level at the call site, not later:
The level belongs to the event, so it is chosen where the macro is written. An event recorded with tracing::info! can never be promoted to ERROR by the subscriber, and an event recorded with tracing::error! can never be hidden by calling it routine. If a line deserves attention at three in the morning, record it with error! from the start.
How tracing Improves on println
The println! macro prints a formatted string to the terminal, and nothing else. It has no level, no structured fields, no filtering, and no way to attach context to the line. For a quick one-off script or a tiny program that prints a result and exits, that is all anyone needs, and println! is the right tool there. It is not broken, and it is not wrong. It is a plain printer, and plain printing is enough when the output is read once by the person who ran the program.
tracing is the structured upgrade for programs that keep running and produce output someone else has to read later. The upgrade has four parts. First, levels let the operator hide detailed lines in normal use and show them while fixing a problem, without editing code. Second, fields attach named data to a line, so a log reader can search for user_id=42 instead of reading every line that mentions a user. Third, spans attach context automatically, so a line recorded deep inside a helper still carries the request it belongs to. Fourth, the subscriber can change the output format, so the same events can be printed as readable text while developing and as JSON for a log collector in production, with no change to the code that records them.
The practical rule is simple. A line that is only ever read by the person sitting at the terminal, in the same minute it was printed, can stay a println!. A line that might be read tomorrow, by someone else, in a file full of lines from other requests, should be a tracing event. The two can live in the same program: a startup banner printed once with println! and every operational line recorded with tracing is a normal combination, and neither tool is misused by the presence of the other.
This side-by-side pair makes the difference visible. Both lines print the same fact, but only the second one carries a level and a field:
fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::TRACE)
.init();
println!("user 42 logged in");
tracing::info!(user_id = 42, "user logged in");
}
Running it prints two lines:
user 42 logged in
2026-11-14T11:47:44.287295Z INFO trace_first_steps: user logged in user_id=42
The first line is a sentence with the number 42 buried inside it. The second line is the same sentence with the level INFO, a timestamp, and the field user_id=42 attached as searchable data. A reader searching a large log file for the user can match on user_id=42 in the second line and find it at once. The first line can only be found by reading sentences and hoping the number appears in a recognizable form. Fields get their full explanation on the events page, and the one-line form shown here is all this page needs.
println in background tasks stays valid:
A spawned task that prints with println! for success and eprintln! for failure is a working pattern, and recording the same lines with tracing does not change what the task must do: catch its own errors and write them down, because the response is already gone. The difference is only what the line carries. A tracing::error! line in a task adds a level, a timestamp, and any fields the task recorded, and it reaches the same terminal through the subscriber. Where plain printing still fits is a short-lived script or a first sketch of a task; where the log has to be searched later, the structured line wins.
The Concept Behind the Crate
A program that runs for hours produces far more output than any person can read line by line. The output is only useful if a reader can ask it questions: show me every error from the last hour, show me everything about user 42, show me the requests that took the longest. Plain text can answer those questions only by pattern matching on sentences, which breaks as soon as two sentences describe the same fact in different words. Structured diagnostics answer them by keeping the facts separate from the sentence, so the same question always finds the same lines.
That is the idea the tracing crate is built around. The code that knows a fact records it as data, at the moment it knows it, and the code that reads the log later queries the data. The message stays human readable, so a person scanning the terminal can still follow what happened, but the fields are there for the machine that searches, filters, and counts. The level is part of the same idea: it is a piece of data about the event, recorded once, that lets every later reader decide how much attention the event deserves.
A beginner mental model is a labelled filing cabinet instead of a pile of loose paper. Plain printing throws every note onto one pile. Structured events file each note with labels for how urgent it is, what it is about, and when it happened. Finding one note in a pile takes a full search every time. Finding one note in a labelled cabinet takes one look at the right drawer.
Why the Crate Is Split in Two
The split between tracing, which records, and tracing-subscriber, which prints, looks like extra work the first time it is seen. It exists because the two jobs change for different reasons. The events a program records are part of its behaviour: what it logs, at which level, with which fields, is a decision about the program itself, and it changes when the program gains a new feature. The way those events are displayed is a decision about the environment: readable text on a developer machine, JSON in a log collector, silence in a test run. That changes when the program moves between machines, not when it gains a feature.
Keeping the two decisions in separate crates means a library can record events without dragging in an opinion about how they should be displayed, and an application can change its output format without touching any of the code that records events. It also means a test can install a subscriber that captures events into memory and asserts on them, while the real program installs a subscriber that prints them, and the code under test never knows the difference. The split costs one extra dependency and one setup line, and it buys the freedom to change either side without touching the other.
A Richer Example in a Small Server
The ideas so far fit in a single file, and they also fit in a real server without any new concepts. This example is a tiny Axum server with one route. It records an INFO event when the server starts, an INFO event inside the handler, and an ERROR event when the handler finds a problem. The Axum parts are the same as any small server: a router, a handler, a listener, and axum::serve. The new parts are only the three tracing macro calls and the subscriber line.
use axum::{routing::get, Router};
use tracing::Level;
async fn hello() -> &'static str {
tracing::info!("hello handler was reached");
"Hello, world!"
}
async fn get_user(axum::extract::Path(id): axum::extract::Path<u64>) -> String {
if id == 0 {
tracing::error!(user_id = id, "refused to look up user zero");
return "No such user".to_string();
}
tracing::info!(user_id = id, "looking up user by id");
format!("User ID: {}", id)
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(Level::DEBUG)
.init();
tracing::info!("server starting");
let app = Router::new()
.route("/", get(hello))
.route("/users/{id}", get(get_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
tracing::info!("server listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
[package]
name = "trace_first_steps"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tracing = "0.1"
tracing-subscriber = "0.3"
Run the server with cargo run, then request the routes from a second terminal with curl http://127.0.0.1:3000, curl http://127.0.0.1:3000/users/42, and curl http://127.0.0.1:3000/users/0. The server terminal shows one line per event, and the shape of each line is the same as the small examples above. The timestamps differ on every run, and the level, target, message, and fields stay the same:
2026-11-14T11:47:44.287223Z INFO trace_first_steps: server starting
2026-11-14T11:47:44.287223Z INFO trace_first_steps: server listening on http://127.0.0.1:3000
2026-11-14T11:47:44.287223Z INFO trace_first_steps: hello handler was reached
2026-11-14T11:47:44.287223Z INFO trace_first_steps: looking up user by id user_id=42
2026-11-14T11:47:44.287223Z ERROR trace_first_steps: refused to look up user zero user_id=0
The startup lines appear once, each request adds its own lines, and the error line for user zero stands out by its level alone, before anyone reads the message. The user_id=42 field on the lookup line and the user_id=0 field on the error line are the same mechanism as the single-field example earlier, now carrying the value the handler actually received. No request context is attached to these lines yet, because no span is active around the handler. Adding that context is the job of spans, and it is what makes the same handler lines searchable by request.
Choosing a Level for Each Message
A level is a judgement about the message, and beginners usually hesitate over which one to pick. Four questions make the choice mechanical. Did something fail and need fixing? That is ERROR. Did something unexpected happen but the program carried on? That is WARN. Is this a normal step the operator wants to see in a healthy run? That is INFO. Is this detail only useful while tracking down a specific problem? That is DEBUG, and the finest grain of that detail is TRACE.
A login that succeeded is INFO. A login that failed because the password was wrong, with the request answered normally, is WARN, because nothing broke but something worth noticing happened. A login that failed because the database was unreachable is ERROR, because the program could not do its job. The number of active connections printed once a minute is DEBUG, because it is only interesting while investigating load. The value of a variable inside a loop that runs a thousand times a second is TRACE, because it would flood the log if it were printed at any higher level.
This example records the same situation at the level it deserves in each case:
fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::TRACE)
.init();
tracing::info!("payment received");
tracing::warn!("payment gateway was slow, retrying");
tracing::error!("payment gateway unreachable after three tries");
tracing::debug!("payment handler took the card path");
tracing::trace!("payment amount in cents is 4999");
}
Each line is a different judgement, not a different severity of the same fact. The INFO line says the business event happened. The WARN line says a step wobbled and recovered. The ERROR line says the step failed outright. The DEBUG and TRACE lines say things only a person debugging the payment flow would want. When the subscriber maximum is INFO, only the first three lines appear, which is exactly the set an operator watching a healthy system needs.
Formatted Messages
An event message can include values, using the same {} placeholders as println!. The values are written after the format string, separated by commas, and they are formatted into the message when the event is recorded. This is the way to put a number that only belongs in the sentence into the sentence, while values that should be searchable go in fields instead.
fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::TRACE)
.init();
let user_id: u64 = 42;
let attempts: u32 = 3;
tracing::info!("user {} logged in after {} attempts", user_id, attempts);
tracing::warn!("retry {} of {} for user {}", attempts, 3, user_id);
}
The output shows the formatted sentences with the values in place:
2026-11-14T11:47:44.287223Z INFO trace_first_steps: user 42 logged in after 3 attempts
2026-11-14T11:47:44.287223Z WARN trace_first_steps: retry 3 of 3 for user 42
The rule for choosing between a formatted value and a field is about who reads it. A value inside the message is for the human reading the line. A value in a field is for the search that finds the line later. The user id in the example above appears in both places in different lines across this page: inside the sentence when the sentence is the point, and as user_id=42 when the line has to be found again. Both forms are correct, and the choice is made line by line.
What Happens with No Subscriber
A program that calls tracing::info! without ever installing a subscriber compiles, runs, and prints nothing. The macro still builds the event record, checks whether any subscriber wants it, finds none, and drops it. There is no panic, no warning, and no error message. This is by design: libraries record events freely, and an application that never installs a subscriber has simply chosen to hear nothing.
fn main() {
tracing::info!("this line is recorded and then dropped");
tracing::error!("this line is recorded and then dropped too");
println!("only this line reaches the terminal");
}
Run this program and the terminal shows exactly one line, the println! line. The two tracing lines vanish. This behaviour was verified by running a program that records events before the subscriber line and after it: the lines recorded before the subscriber is installed never appear, and the lines recorded after it appear normally. The lesson is about order: the subscriber line must run before the first event that matters, which is why it sits at the very top of main in every example on this page.
No subscriber means no output, not a broken macro:
If cargo run prints nothing from tracing calls, do not rewrite the macro calls. Check first that tracing_subscriber::fmt().init() runs before them. The compiler cannot warn about a missing subscriber, because recording events without a subscriber is a valid choice for a library. In an application, it is almost always a mistake.
The Target of an Event
Every printed line shows a target after the level, and in the examples so far that target is the crate name, such as trace_first_steps. The target is the module path where the macro was called, and it tells the reader which part of the program produced the line. A call in src/main.rs at the crate root shows the crate name. A call inside a module named handlers shows trace_first_steps::handlers. The target is recorded automatically, so the programmer never writes it, but it matters when reading logs, because it separates lines from different parts of the program even when the messages look alike.
The target can also be set by hand for a single event, using the target: form of the macro. That is rarely needed, and the normal case is to let the module path speak for itself. The form is shown here once so it is recognised when it appears in other code:
fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::TRACE)
.init();
tracing::info!(target: "payments", "payment received");
}
The printed line carries payments as the target instead of the crate name. Use this only when a line genuinely belongs to a named area that does not match any module, such as a subsystem that spans several modules. For ordinary code, the module path is the right target, and inventing custom targets makes logs harder to filter, not easier.
The Event Flow
The path an event takes from the macro call to the terminal has four steps, and each step is owned by a different piece:
Code calls tracing::info!
|
v
tracing builds the event record (level, message, fields, location)
|
v
The active subscriber checks the level against its maximum
|
v
Accepted events are formatted and printed, the rest are dropped
Nothing in this flow is stored unless a subscriber stores it. The fmt subscriber prints each accepted event once and forgets it. A different subscriber could write it to a file or send it to another service, and the code that recorded the event would not change. That is the whole point of the split: the recording side stays the same while the handling side varies.
Testing Events
A test cannot read the terminal, so it needs a subscriber that writes into memory instead. The tracing-subscriber crate accepts any writer, and a small wrapper type can collect the output into a shared buffer that the test then reads. The wrapper below implements the two traits the subscriber needs: std::io::Write, which appends bytes to the buffer, and MakeWriter, which hands the subscriber a fresh handle to the same buffer each time it writes.
use std::io::Write;
use std::sync::{Arc, Mutex};
use tracing::{info, Level};
use tracing_subscriber::fmt::writer::MakeWriter;
#[derive(Clone, Default)]
struct BufWriter(Arc<Mutex<Vec<u8>>>);
impl Write for BufWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<'a> MakeWriter<'a> for BufWriter {
type Writer = Self;
fn make_writer(&'a self) -> Self::Writer {
self.clone()
}
}
fn read(buf: &BufWriter) -> String {
String::from_utf8(buf.0.lock().unwrap().clone()).unwrap()
}
#[test]
fn info_event_reaches_the_writer() {
let buf = BufWriter::default();
let subscriber = tracing_subscriber::fmt()
.with_max_level(Level::TRACE)
.with_ansi(false)
.with_writer(buf.clone())
.finish();
tracing::subscriber::with_default(subscriber, || {
info!(user_id = 42, "user logged in");
});
let text = read(&buf);
assert!(text.contains("user logged in"));
assert!(text.contains("user_id=42"));
}
#[test]
fn level_filter_disables_debug_events() {
let buf = BufWriter::default();
let subscriber = tracing_subscriber::fmt()
.with_max_level(Level::INFO)
.with_ansi(false)
.with_writer(buf)
.finish();
tracing::subscriber::with_default(subscriber, || {
assert!(tracing::enabled!(Level::INFO));
assert!(!tracing::enabled!(Level::DEBUG));
assert!(!tracing::enabled!(Level::TRACE));
});
}
The test needs tracing and tracing-subscriber as dependencies, the same ones the program uses. The with_default call installs the capturing subscriber only for the duration of the closure, which keeps tests independent of each other: each test builds its own subscriber and its own buffer, and no test touches the global subscriber. The .with_ansi(false) call matters for the assertions, because the default formatter adds colour codes around field names, and those codes would sit inside the text the test searches. The tracing::enabled! macro in the second test asks the current subscriber whether a level would be recorded, which is the honest way to test filtering without printing anything. Run the tests with cargo test and both pass, as verified against the scratch project used for this page.
Common Beginner Mistakes
Forgetting the subscriber
// Wrong - compiles and runs, prints nothing
fn main() {
tracing::info!("server started");
}
The macro call is correct and the program is correct, but no subscriber exists, so the event is dropped. Add tracing_subscriber::fmt().init() as the first line of main, before any event that should be seen.
Initialising the subscriber after the first events
// Wrong - the first line is recorded before output is switched on
fn main() {
tracing::info!("server starting");
tracing_subscriber::fmt().init();
tracing::info!("server started");
}
Only the second line appears. The first event was recorded while no subscriber was active, and it cannot be recovered. The subscriber line belongs at the very top of main, above every other statement that records an event.
Expecting DEBUG lines from a plain subscriber
// Wrong expectation - this line is filtered out by the default INFO maximum
fn main() {
tracing_subscriber::fmt().init();
tracing::debug!("detailed state while debugging");
}
The plain subscriber prints INFO and above. A DEBUG event is recorded and then dropped by the level filter. Raise the maximum with .with_max_level(tracing::Level::DEBUG) while debugging, or record the line at INFO if it belongs in normal output.
Using println for lines that need levels
// Wrong shape for operational output - no level, no filtering, no fields
println!("ERROR: database connection failed");
The word ERROR inside a sentence is not a level. The subscriber cannot filter on it, a log tool cannot count it, and a reader cannot hide it. Record it with tracing::error!("database connection failed") instead, and let the level do the work the capital letters were doing.
Confusing the message with the fields
// Weak - the user id is buried in the sentence and cannot be searched for
tracing::info!("user 42 logged in");
The line works, and the sentence reads well, but a search for user_id=42 finds nothing. When a value identifies the work, record it as a field as well: tracing::info!(user_id = 42, "user logged in"). The message stays readable and the value becomes searchable.
A level is not a decoration:
Writing tracing::error! for routine lines trains everyone to ignore ERROR lines, and writing tracing::info! for real failures hides them among routine lines. The level system only works when each call site tells the truth about what happened. When the choice is unclear, ask whether the line should wake someone up. If yes, it is ERROR. If it should be noticed in the morning, it is WARN. If it is normal operation, it is INFO.
Final Complete Example
This example pulls the page together: a small program that records events at several levels, uses fields for the values that identify the work, formats a value into a message, and shows what the subscriber prints for each one.
use tracing::Level;
fn process_payment(user_id: u64, amount_cents: u64) {
tracing::info!(user_id, amount_cents, "payment received");
tracing::debug!(user_id, "payment handler took the card path");
if amount_cents == 0 {
tracing::warn!(user_id, "payment of zero cents received");
}
}
fn main() {
tracing_subscriber::fmt()
.with_max_level(Level::TRACE)
.init();
tracing::info!("server started");
process_payment(42, 4999);
process_payment(7, 0);
tracing::error!("database connection failed, retrying in 5 seconds");
tracing::trace!("shutdown check complete");
}
[package]
name = "trace_first_steps"
version = "0.1.0"
edition = "2021"
[dependencies]
tracing = "0.1"
tracing-subscriber = "0.3"
Run it with cargo run. The terminal shows the INFO startup line, two payment lines with their fields, the DEBUG line inside the payment handler, the WARN line for the zero payment, the ERROR line for the database, and the TRACE line at the end. The field shorthand user_id without = value works because a variable with the same name is in scope, and the field takes the variable name and its value together. Every line carries its level, so a reader scanning the output can tell at a glance which lines are routine and which ones need attention, without reading a single message.
Summary
The decision this page teaches is what a diagnostic line should carry, and the answer is three things: a level that says how much attention it deserves, a message a human can read, and fields a machine can search. The tracing crate records those three things and nothing else, and a subscriber decides what happens to them. That split is what makes the same code work in development, in tests, and in production: the recording stays fixed while the handling changes with the environment.
The framework for choosing between the tools is the lifetime of the line. If the line is read once, by the person who ran the program, in the same minute, plain printing is enough. If the line might be read tomorrow, by someone else, among lines from other requests, record it as an event with a level and fields. And once events are in place, the question that decides what to build next is which lines belong together. A single event says one thing happened. A group of events that belong to one piece of work needs a container that holds them together and stamps them with the same context, and that container is a span.