Structured JSON log output
Learn how to switch tracing output to structured JSON lines with tracing-subscriber, read every key in a JSON log line, and shape the output for log search tools
A JSON log line is one log event written as a single JSON object. Each line carries the same facts a human readable line carries, but as named keys and values a program can read without guessing. The timestamp is a key called timestamp. The level is a key called level. The message and every extra value live inside a key called fields. A log collection tool reads each line, parses the JSON, and lets you search by key, so finding every error for one user becomes a filter instead of a text search.
Where This Fits
The request span already groups log lines by request, with the method, URI, and version attached to each line. JSON output takes that same context and turns it into keys. The span fields stop being text inside a prefix and become entries in two JSON objects, span and spans, that a search tool can filter on directly. The span itself does not change. Only the way it is printed changes, from text a person scans to JSON a machine parses.
Think of the difference between a handwritten note and a form with labelled boxes. The note says everything in sentences, and a reader has to parse the sentences to find the date or the amount. The form has a box labelled date and a box labelled amount, and anyone can read the right box at once. Human readable logs are the note. JSON logs are the form.
The Smallest Working Version
One method call changes the format. The subscriber builder has a method called .json(), and calling it before .init() switches the whole output from text lines to JSON lines. Everything else in the program stays the same.
Create a project with cargo new json-log-demo and replace the generated Cargo.toml with this one:
[package]
name = "json-log-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
The json feature on tracing-subscriber is what makes the .json() method exist. Without it, the method is not compiled and the code fails with an error saying no method named json was found. The env-filter feature is used later on this page, when the level is controlled from the RUST_LOG environment variable.
The smallest program is a server with one route. The handler logs one line with two extra fields, a user id and an action name:
use axum::{routing::get, Router};
async fn checkout() -> &'static str {
tracing::info!(user_id = 42, action = "checkout_started", "checkout started");
"Order confirmed"
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt().json().init();
let app = Router::new().route("/checkout", get(checkout));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("server listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run the server with cargo run, then send a request with curl http://127.0.0.1:3000/checkout from a second terminal. The server terminal shows one line, verified by running this program:
{"timestamp":"2026-11-14T11:48:23.555393Z","level":"INFO","fields":{"message":"checkout started","user_id":42,"action":"checkout_started"},"target":"t14_plain"}
That is the whole line. It is valid JSON, and it fits on one line with no line breaks inside it. The response in the curl terminal is Order confirmed, as usual. The log line is the only thing that changed.
How to tell JSON output is working:
If the server terminal shows a line that starts with {"timestamp": and ends with }, JSON output is working. Paste the line into python3 -m json.tool or jq . and it prints as a readable multi-line object. If the line starts with a date and a level word instead, the .json() call is missing or the wrong subscriber is being initialised.
The target value is your crate name:
The target value in the line above reads t14_plain because that was the name of the test program that produced the output. In your own project it reads your own crate name, which is the name field in your Cargo.toml, with hyphens turned into underscores. A log line from a handler in a submodule reads the full module path, such as json_log_demo::handlers.
Reading One JSON Line Key by Key
A JSON log line has a fixed set of top level keys. Each one answers one question about the event, and a beginner who can read these keys can read any JSON log line from any Rust server.
The timestamp key holds the time the event was written, in UTC, with microsecond precision. The value looks like 2026-11-14T11:48:23.555393Z. The T separates the date from the time, and the Z at the end means UTC, the timezone log tools use so that servers in different places can be compared. You never have to parse this by hand. A search tool reads it as a time and lets you filter by time range.
The level key holds the level of the event as a string, one of TRACE, DEBUG, INFO, WARN, or ERROR. Levels decide which lines survive filtering, and a later section on this page shows how the level setting hides lower lines. The level is a plain string in JSON, so a search tool can filter with an exact match on level == "ERROR".
The fields key holds an object with the message and every extra value the log call recorded. The message is always under the key message. Extra values appear under their own names, with their real JSON types: user_id is the number 42, not the string "42", and action is the string "checkout_started". That typing matters. A search tool can compare user_id as a number, so a filter for users above 100 works, and it can match action as a string. If the values were baked into one text message, the tool would have to guess where the number ends.
The target key holds the module path the event came from, usually the crate name. It tells you which part of the code wrote the line. In a program with several crates, the target is the fastest way to tell your own log lines apart from lines written by a library.
Two more keys appear when a span is active, and they are the reason this page pairs with the request span. The span key holds the fields of the innermost span the event was written inside, and the spans key holds a list of all spans from the outermost to the innermost. A span is a named unit of work with a start and an end, and the request span is the one the tracing layer opens for each HTTP request. Both keys are missing from the line above, because the smallest program has no span and the default level hides the request span, which is a trap the next sections explain in full.
The order of keys inside the JSON objects is alphabetical, because the formatter serialises the fields in sorted order. The span object in the examples below shows method, then request_id, then uri, then name, even though the code wrote them in a different order. Do not rely on key order. Read JSON by key name, never by position.
The Concept Behind Structured Logging
A log line has two readers, and they want opposite things. A person reading a terminal wants short text they can scan by eye. A log collection tool wants data it can index without guessing. One format cannot serve both readers well, so programs pick a format per reader: text while a person is watching, JSON when a tool is collecting.
JSON wins for the tool because every fact has a name and a type. A text line like checkout started user_id=42 still needs a parser that knows user_id=42 is a number attached to a message. A JSON line states it outright: the field named user_id holds the number 42. There is nothing to parse and nothing to misread. A field that is missing is simply absent from the object, instead of being an empty gap in a text pattern.
The format has one more property that matters in production. Each event is exactly one line, with no line breaks inside it. That shape has a name, newline-delimited JSON, often written as NDJSON or JSONL. A log shipper reads the output line by line, parses each line on its own, and sends it on. If one line is damaged, only that line is lost. A pretty printed JSON object spread over ten lines would break that flow, because the shipper could not tell where one event ends and the next begins.
A mental model that helps is a spreadsheet row. Each log line is one row. Each key is a column. The timestamp column holds times, the level column holds levels, the fields column holds a small bag of extra columns. Searching the logs is filtering the spreadsheet by column values. Text logs are a pile of sticky notes instead, and finding every note for one user means reading all of them.
Why JSON Instead of Text in Production
A server in production is not watched by a person. Its logs go to a file or a collection service, and a person only looks at them after something goes wrong. At that moment the question is always a filter: show me every error from the last hour, show me every line for this user, show me every request slower than a threshold. JSON answers those questions with exact key matches. Text answers them with pattern matching, which is slower to write and easier to get wrong.
JSON also survives change better. Adding a new field to a log call adds a new key to the object, and old search queries keep working because the keys they use are still there. Adding a word to a text message can break a pattern that matched the old wording. The structured form treats the log as data from the start, so growing it does not break the tools that read it.
None of this makes text output wrong. Text is the better choice while developing, because a person is the reader and the eye is the tool. The decision is about the reader, not about the format being better in itself. A server whose logs are read by a person uses text. A server whose logs are read by a tool uses JSON.
A Richer Example with the Request Span
The smallest example shows the keys, but it shows no span, because it has no tracing layer and no span. The realistic version adds the request span, so the JSON lines carry the method, URI, and version of the request that produced them. This is the program the rest of the page builds on.
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
async fn checkout() -> &'static str {
tracing::info!(user_id = 42, action = "checkout_started", "checkout started");
tracing::debug!(cart_items = 3, "cart contents checked");
tracing::info!(user_id = 42, action = "checkout_done", "checkout finished");
"Order confirmed"
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.json()
.with_max_level(tracing::Level::DEBUG)
.init();
let app = Router::new()
.route("/checkout", get(checkout))
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("server listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The new parts are the TraceLayer on the router and the .with_max_level(tracing::Level::DEBUG) call on the subscriber. The layer opens one span per request, named request, and records the method, URI, and HTTP version inside it. The max level call matters because the span and the layer own events are DEBUG level, and a plain subscriber stops at INFO. Both parts are explained in detail below.
One request to /checkout produces six JSON lines, verified by running this program. The println! startup line is not shown here, because it is plain text, not JSON. The lines are shown in full, with only the timestamp values shortened in the second and later lines so the page stays readable:
{"timestamp":"2026-11-14T11:48:14.877502Z","level":"DEBUG","fields":{"message":"started processing request"},"target":"tower_http::trace::on_request","span":{"method":"GET","uri":"/checkout","version":"HTTP/1.1","name":"request"},"spans":[{"method":"GET","uri":"/checkout","version":"HTTP/1.1","name":"request"}]}
{"timestamp":"...","level":"INFO","fields":{"message":"checkout started","user_id":42,"action":"checkout_started"},"target":"t14","span":{"method":"GET","uri":"/checkout","version":"HTTP/1.1","name":"request"},"spans":[{"method":"GET","uri":"/checkout","version":"HTTP/1.1","name":"request"}]}
{"timestamp":"...","level":"DEBUG","fields":{"message":"cart contents checked","cart_items":3},"target":"t14","span":{"method":"GET","uri":"/checkout","version":"HTTP/1.1","name":"request"},"spans":[{"method":"GET","uri":"/checkout","version":"HTTP/1.1","name":"request"}]}
{"timestamp":"...","level":"INFO","fields":{"message":"checkout finished","user_id":42,"action":"checkout_done"},"target":"t14","span":{"method":"GET","uri":"/checkout","version":"HTTP/1.1","name":"request"},"spans":[{"method":"GET","uri":"/checkout","version":"HTTP/1.1","name":"request"}]}
{"timestamp":"...","level":"DEBUG","fields":{"message":"finished processing request","latency":"0 ms","status":200},"target":"tower_http::trace::on_response","span":{"method":"GET","uri":"/checkout","version":"HTTP/1.1","name":"request"},"spans":[{"method":"GET","uri":"/checkout","version":"HTTP/1.1","name":"request"}]}
{"timestamp":"...","level":"DEBUG","fields":{"message":"end of stream","stream_duration":"0 ms"},"target":"tower_http::trace::on_eos","span":{"method":"GET","uri":"/checkout","version":"HTTP/1.1","name":"request"},"spans":[{"method":"GET","uri":"/checkout","version":"HTTP/1.1","name":"request"}]}
Every line carries the same span and spans values, because every event happened inside the same request span. The handler lines are the two INFO lines and the one DEBUG line in the middle, with the user_id, action, and cart_items fields inside fields. The other three lines come from the tracing layer itself: it announces the request, the response with its latency and status, and the end of the response stream. The latency value is the string "0 ms" and the status value is the number 200, which is how the formatter writes those two values.
Two details in the output deserve attention. The target of the handler lines is the crate name, while the target of the layer lines is tower_http::trace::on_request, tower_http::trace::on_response, and tower_http::trace::on_eos. The target tells you who wrote each line, which is how you separate your own lines from the layer lines when searching. And the span and spans objects are identical on every line here, because there is only one span. With nested spans, span holds the innermost one and spans lists all of them from the outermost to the innermost, in that order.
The Plain JSON Subscriber Trap
The most common JSON surprise is running the richer example with a plain subscriber, meaning tracing_subscriber::fmt().json().init() with no .with_max_level call, and seeing output that looks broken. It is not broken. It is filtered. This was verified by running the same server twice, once with each subscriber.
With a plain .json().init() subscriber, whose maximum level is INFO, a single request produces exactly one line:
{"timestamp":"2026-11-14T11:48:23.555393Z","level":"INFO","fields":{"message":"checkout started","user_id":42,"action":"checkout_started"},"target":"t14_plain"}
The handler INFO line appears, but with no span key and no spans key, and no started or finished lines anywhere. The reason is the level system. The request span is DEBUG level, so at an INFO maximum the span is disabled entirely, and an event with no active span prints with no context. The layer own events are DEBUG level too, so they are filtered out as well. Nothing is wrong with the formatter. The subscriber is simply not letting DEBUG output through.
There are two fixes, and they solve different problems. The first fix is to lower the subscriber maximum to DEBUG, with .with_max_level(tracing::Level::DEBUG), which is what the richer example does. That shows everything, the span context and the layer own events. The second fix is to raise the span level to INFO, so the span survives an INFO maximum while the layer own DEBUG events stay hidden. The span level is set where the span is created, and the request span is created by the tracing layer, so the fix is a custom span maker that uses tracing::info_span! instead of the default. The code for that appears in the page about correlating logs with a request id, where the span is built by hand.
A missing span key means the level filtered the span:
If your JSON lines have no span key, check the subscriber maximum level before changing the formatter. A DEBUG span under an INFO maximum is disabled, and a disabled span leaves no trace in the output. The formatter cannot print context that was never recorded.
Flattening the Event Fields
By default the message and the extra values sit inside the fields object, one level down from the top. Some log tools prefer a flatter shape, with the message and the values at the top level next to timestamp and level. The .flatten_event(true) method does that. It is a builder method on the JSON formatter, called after .json().
tracing_subscriber::fmt()
.json()
.flatten_event(true)
.with_span_list(false)
.with_max_level(tracing::Level::DEBUG)
.init();
This subscriber also turns the span list off, with .with_span_list(false), so the example shows two changes at once. Run the same checkout program with this subscriber and one request produces lines like these, verified by running the program:
{"timestamp":"2026-11-14T11:49:13.681691Z","level":"DEBUG","message":"started processing request","target":"tower_http::trace::on_request","span":{"method":"GET","uri":"/checkout","version":"HTTP/1.1","name":"request"}}
{"timestamp":"...","level":"INFO","message":"checkout started","user_id":42,"target":"t14_var","span":{"method":"GET","uri":"/checkout","version":"HTTP/1.1","name":"request"}}
{"timestamp":"...","level":"DEBUG","message":"finished processing request","latency":"0 ms","status":200,"target":"tower_http::trace::on_response","span":{"method":"GET","uri":"/checkout","version":"HTTP/1.1","name":"request"}}
The fields key is gone. The message moved to the top level, and so did user_id, latency, and status. The spans key is gone too, while the span key stays, because only the span list was turned off. Flattening changes where values sit, not which values exist. A query that read .fields.user_id now reads .user_id, and a query that read .fields.message now reads .message.
Pick the flat shape when the tool reading the logs expects top level fields, or when the team writes queries by hand and shorter paths are easier to type. Keep the default nested shape when the tool already expects a fields object, or when several systems share the same logs and the nested shape is the agreed format. The two shapes carry the same information, so the choice is about the reader, not about the data.
Turning the Span Keys Off
The formatter has two more switches, one for each span key. The .with_current_span(false) method removes the span key, and .with_span_list(false) removes the spans key. Both default to true, which means both keys are printed. The switches exist because the two keys serve different readers, and some setups need only one of them.
The span key is the one most searches use. It holds the innermost span, which for a web server is the request span, so a filter on span.uri finds every line for one path. The spans key is the full chain from the outermost span to the innermost, which matters when spans nest, for example a request span containing a database span containing a query span. A reader that only needs the request context can turn the list off and save the repeated bytes on every line. A reader that traces work through nested spans keeps the list.
The combination used most in production is the current span on and the span list off, because the request span is the one that matters and the list usually repeats it. The code for that combination is one line on the builder:
tracing_subscriber::fmt()
.json()
.with_span_list(false)
.init();
Turning both keys off is also valid, and it makes sense for a program with no spans at all, where the keys would never appear anyway. Turning the current span off while keeping the list is the unusual choice, and it only fits a tool that reads the whole chain and ignores the single span. There is no wrong combination, but there is a wasteful one: keeping the list on when the program never nests spans, because every line then carries the same object twice.
Turning a key off removes it, it does not empty it:
With .with_span_list(false) the spans key is absent from the line entirely. It does not appear as an empty list. A query that reads .spans[0] on such a line finds nothing, so check the shape your subscriber produces before writing queries against it.
Controlling the Level from the Environment
A subscriber built with .with_max_level fixes the level in code, which means changing the level needs a rebuild. Production servers change their level without rebuilding, by reading it from the RUST_LOG environment variable. The EnvFilter type does that reading, and the builder method .with_env_filter installs it. The env-filter feature in Cargo.toml is what makes the type available.
tracing_subscriber::fmt()
.json()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.init();
The try_from_default_env call reads RUST_LOG. If the variable is not set, the fallback filter of info is used, so only INFO, WARN, and ERROR events appear. Run the server normally with cargo run and the DEBUG lines stay hidden. Run it with RUST_LOG=debug cargo run and the DEBUG lines appear, including the request span context. The filter replaces the max level, so do not call both .with_max_level and .with_env_filter on the same builder. The second call wins and the first is silently dropped.
The filter accepts per-crate levels too, as a comma separated list. The value RUST_LOG=my_app=debug,tower_http=warn shows DEBUG lines from your own crate but only WARN and ERROR from the tracing layer crate. Replace my_app with your own crate name, with hyphens turned into underscores. That split is the practical answer to the volume problem: your own detail stays visible while the layer own DEBUG lines stay quiet.
Writing JSON Logs to a File
The formatter writes to standard output by default, which is the right place when a container runtime or a log shipper collects the output. Some deployments want the logs in a file instead, and the .with_writer method redirects the output. It takes anything that can receive bytes, and a std::fs::File is the straightforward choice.
use std::fs::File;
#[tokio::main]
async fn main() {
let log_file = File::create("server-json-logs.jsonl").unwrap();
tracing_subscriber::fmt()
.json()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.with_writer(log_file)
.init();
let app = Router::new()
.route("/checkout", get(checkout))
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("server listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
With this subscriber the terminal shows only the println! startup line, and every JSON line goes into server-json-logs.jsonl instead. The file has the .jsonl extension because each line is one JSON object, which is the newline-delimited JSON shape described earlier. Run the server with RUST_LOG=debug and the file holds the full set of lines, including the DEBUG layer events. This was verified by running the program: the file held five lines for one request, each with a spans key and no span key, because that run also used .with_current_span(false).
A file writer and a stdout writer are not exclusive in a real deployment. The usual shape is one subscriber writing JSON to a file that a shipper tails, while the terminal keeps only the startup message. Rotating the file, meaning starting a fresh file when the old one grows too large, is a job for the deployment, not for the subscriber. The subscriber only writes bytes to the file it was given.
A plain println in the same stream breaks JSON parsing:
The startup println! writes plain text to standard output, and the JSON lines go to the same stream by default. A tool that parses the whole stream as JSON fails on that first text line. Either write the logs to a file, as above, or filter the stream to JSON lines before parsing. The examples below show the filter.
Reading JSON Logs with jq
JSON logs are written for tools, and jq is the smallest such tool. It is a command line program that reads JSON, filters it, and prints the result. The three commands below cover the questions a beginner asks first, and each one was run against real output from the richer example.
Pretty print one line, so the keys are easy to read while learning:
grep '^{' server-json-logs.jsonl | head -1 | jq .
The grep '^{' step keeps only lines that start with a {, which drops the plain text startup line that would otherwise make jq fail with a parse error. That failure is the trap from the previous section, and the grep is the fix when logs and text share one stream. The output is the same line with indentation:
{
"timestamp": "2026-11-14T11:48:14.877502Z",
"level": "DEBUG",
"fields": {
"message": "started processing request"
},
"target": "tower_http::trace::on_request",
"span": {
"method": "GET",
"uri": "/checkout",
"version": "HTTP/1.1",
"name": "request"
},
"spans": [
{
"method": "GET",
"uri": "/checkout",
"version": "HTTP/1.1",
"name": "request"
}
]
}
Show only the messages of the INFO lines, which is the fastest way to read what the server did:
grep '^{' server-json-logs.jsonl | jq -r 'select(.level == "INFO") | .fields.message'
Against the richer example this prints checkout started and checkout finished, one per line. The select keeps only lines whose level is INFO, and .fields.message prints the message without quotes because of the -r flag.
Show only the errors, which is the command run first when something goes wrong:
grep '^{' server-json-logs.jsonl | jq -c 'select(.level == "ERROR")'
The -c flag keeps each matching line compact, one JSON object per line, so the output stays pipeable into the next tool. Against the richer example this prints nothing, because the program logged no errors, and an empty result is the correct answer, not a broken command.
How a JSON Line Travels
The path from a log call to a searchable line has five stops, and each stop does one job:
tracing::info! call in the handler
|
v
event is created with fields and the active span
|
v
subscriber checks the level, drops the event if it is too low
|
v
JSON formatter writes one line with timestamp, level, fields, target, span, spans
|
v
line goes to stdout, a file, or a collector that parses and indexes it
The level check happens before formatting, which is why a filtered event costs almost nothing and leaves no trace. The formatter only runs for events that survive. The collector at the end is any tool that reads lines and indexes keys: a local file searched with jq, or a hosted log service. The shape of the line is the same in both cases, which is the point of the format. The program does not know or care which tool reads it.
Testing That JSON Output Is Well Formed
A test cannot easily read the server terminal, but it can read a file the subscriber wrote. The test below builds a JSON subscriber that writes to a file, logs one INFO line and one ERROR line with a max level of ERROR, then reads the file back and checks the shape. The INFO line must be absent, because the max level filtered it, and the ERROR line must parse as JSON with the right keys.
use std::fs::File;
#[test]
fn json_lines_parse_and_carry_level() {
let path = "target/test-json-logs.jsonl";
let file = File::create(path).unwrap();
let subscriber = tracing_subscriber::fmt()
.json()
.with_writer(file)
.with_max_level(tracing::Level::ERROR)
.finish();
tracing::subscriber::with_default(subscriber, || {
tracing::info!("this info line must be filtered out");
tracing::error!(reason = "db down", "checkout failed");
});
let text = std::fs::read_to_string(path).unwrap();
assert_eq!(text.lines().count(), 1);
let value: serde_json::Value =
serde_json::from_str(text.lines().next().unwrap()).unwrap();
assert_eq!(value["level"], "ERROR");
assert_eq!(value["fields"]["reason"], "db down");
assert!(value["timestamp"].is_string());
}
The subscriber is built with .finish() instead of .init(), because a test must not install a global subscriber that other tests could clash with. The with_default call runs the closure with this subscriber active only inside the closure, and then restores whatever was there before. The file is read back after the closure returns, so the writes have finished. The assertions check three things: exactly one line survived, it parses as JSON, and the level and the extra field hold the values the log call recorded.
This test needs serde_json as a dependency, which is listed in the Cargo.toml of the final complete example below, and no extra dev dependency. Run it with cargo test, and the output ends with test result: ok. The test was run against this exact code and passed.
A file writer makes log tests possible:
A subscriber writing to standard output cannot be read back by a test, because the test and the program share the terminal. A subscriber writing to a file can, because the test reads the file after the log calls run. That is the practical reason the file writer appears on this page twice, once for production and once for testing.
Common Beginner Mistakes
Forgetting the json feature
// Wrong - will not compile without the feature
tracing_subscriber::fmt().json().init();
With tracing-subscriber = "0.3" and no features listed, the .json() method does not exist, and the compiler reports that no method named json was found. Add features = ["json"] to the dependency. The same rule applies to env-filter: the EnvFilter type only exists when that feature is on.
Expecting the span keys at the default level
// Wrong expectation - the span is DEBUG level, the subscriber stops at INFO
tracing_subscriber::fmt().json().init();
A plain .json().init() subscriber has a maximum level of INFO, and the request span is DEBUG level, so the span and spans keys never appear. The fix is .with_max_level(tracing::Level::DEBUG) while developing, or a span built at INFO level in production. The trap section above shows both fixes and the exact output of each.
Logging secrets as fields
// Wrong - a password in a field is a password in every stored log line
tracing::info!(password = "hunter2", "user logged in");
Fields are data, and data in a log line is stored wherever the logs go, often for a long time and often readable by people who should never see a password. A field holding a token, a password, or a full authorization header turns the log store into a secret store. Log the fact that a login happened and the user id, never the credential itself. The same care applies to the request headers: recording every header in a span can leak the authorization header into the logs.
Mixing println with JSON on the same stream
// Wrong for a JSON pipeline - this text line breaks a strict JSON parser
println!("server listening on http://127.0.0.1:3000");
The startup message is useful for a person and harmful for a parser, when both share standard output. Keep the message and write the logs to a file, or drop the message once the server runs under a collector. A JSON stream must contain only JSON lines, one per line, with nothing else mixed in.
Pretty printing JSON in production
A JSON formatter that spreads each event over several indented lines looks pleasant and breaks the one line per event rule. The tracing-subscriber JSON formatter always writes one line per event, which is the correct shape. If a different tool pretty prints the output before the collector reads it, the collector sees one event as many lines and parses each one as a broken object. Pretty print only when a person is reading, with jq ., and keep the stored lines compact.
Final Complete Example
This example pulls the page together: a checkout server with JSON output, the level read from the environment, logs written to a file, the request span from the tracing layer, and structured fields in every handler line.
use axum::{routing::get, Router};
use std::fs::File;
use tower_http::trace::TraceLayer;
async fn checkout() -> &'static str {
tracing::info!(user_id = 42, action = "checkout_started", "checkout started");
tracing::debug!(cart_items = 3, "cart contents checked");
tracing::info!(user_id = 42, action = "checkout_done", "checkout finished");
"Order confirmed"
}
async fn health() -> &'static str {
tracing::debug!("health check answered");
"OK"
}
#[tokio::main]
async fn main() {
let log_file = File::create("server-json-logs.jsonl").unwrap();
tracing_subscriber::fmt()
.json()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.with_span_list(false)
.with_writer(log_file)
.init();
let app = Router::new()
.route("/checkout", get(checkout))
.route("/health", get(health))
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("server listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
[package]
name = "json-log-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower-http = { version = "=0.7.1", features = ["trace"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
serde_json = "1"
Run the server, then send a request to each route:
curl http://127.0.0.1:3000/checkout
curl http://127.0.0.1:3000/health
The terminal shows only the startup line. The file server-json-logs.jsonl holds the JSON lines, one per event, with the span context on the handler lines when the level allows it. Run with RUST_LOG=debug to see the DEBUG lines and the span keys. Run with no RUST_LOG set to see only the INFO handler lines, with no span keys, which is the plain subscriber trap in action. Read the file with the jq commands above, and the shape of each line tells you which setting produced it.
Summary
The decision this page leaves behind is about the reader, not the format. While a person watches the terminal, human readable text is the right output, because the eye is the tool and short lines scan fastest. Once the logs leave the terminal for a file or a collection service, JSON is the right output, because the reader is a program and named keys with real types are what a program needs.
The framework for the settings is short. Keep the default nested shape unless the reading tool asks for flat fields. Keep the current span and drop the span list unless spans nest. Control the level from RUST_LOG so the level can change without a rebuild, and remember that a DEBUG span under an INFO maximum leaves no span key at all. Write the logs to a file when a parser reads them, so a plain text startup line never breaks the stream. The formatter itself never changes across these choices. One method call, .json(), plus the level and the writer, decides everything a reader of the logs will see.