JSON Logs in Rust, With the Level in a Config File Instead of RUST_LOG

Structured JSON logs with tracing in a Rust backend: a log level read from the same TOML file as everything else, fields instead of sentences, the error that only shows up in tests, and the rule for which errors deserve a log line.

Simone Negro, Backend & AI Developer
6 min read

My readiness endpoint answered 503 when the database was down, which was correct, and told nobody why, which was not. The reason has to go somewhere, and it can’t go into the response. So the backend needed logs, and I wanted them as JSON from day one, with the level set in the same config file as everything else.

This post covers why not RUST_LOG, how a log level becomes a type, the error that only appears in tests, why every event has a fixed message and separate fields, and which errors deserve a log line at all. As in the rest of this series, the examples come from a small demo service, and the log lines below are the ones it actually wrote.

Why not RUST_LOG

The usual way to set the level with tracing is the RUST_LOG environment variable. I already decided that the whole configuration lives in one TOML file, with nothing overriding it, because a variable changed on a server leaves no trace in git. The log level is configuration, so it goes in the file:

log_level = "info"

On my machine I sometimes want debug, to see every query sqlx sends. On a server I want info. Changing it is a one-line edit and a restart, with a commit that says who changed it and when.

A log level is a type, and From converts it

The level in the file is read into an enum, so serde rejects anything that isn’t one of the five values:

#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
enum LogLevel {
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}

tracing-subscriber doesn’t know my enum, it wants a LevelFilter. The idiomatic bridge is the standard From trait:

impl From<LogLevel> for LevelFilter {
    fn from(level: LogLevel) -> Self {
        match level {
            LogLevel::Error => LevelFilter::ERROR,
            LogLevel::Warn => LevelFilter::WARN,
            LogLevel::Info => LevelFilter::INFO,
            LogLevel::Debug => LevelFilter::DEBUG,
            LogLevel::Trace => LevelFilter::TRACE,
        }
    }
}

It took me three tries. On the first, I declared a trait called From instead of implementing the one in the standard library. Mine had nothing to do with the real one, so the standard conversion still didn’t exist:

error[E0277]: the trait bound `LevelFilter: std::convert::From<LogLevel>` is not satisfied

On the second I wrote the implementation backwards, impl From<LogLevel> for LogLevel, which means “a LogLevel can be built from a LogLevel”. The standard library already says that about every type, and Rust refuses two implementations of the same thing:

error[E0119]: conflicting implementations of trait `From<LogLevel>` for type `LogLevel`
  = note: conflicting implementation in crate `core`:
          - impl<T> From<T> for T;

The type after for is the one you get at the end. The type inside From<...> is the one you start from.

LevelFilter rather than Level is deliberate too. A Level is the level of one event (“this is a warning”). A LevelFilter is a threshold (“write everything from warnings up”), and a threshold is what the config value means.

a global default trace dispatcher has already been set

With the conversion in place, setting up JSON output is one chain:

tracing_subscriber::fmt()
    .json()
    .with_max_level(LevelFilter::from(config.log_level))
    .try_init()
    .ok();

The subscriber is global: it’s installed once for the whole process, and from then on every info! or warn! anywhere in the code finds it without being passed anything. “Once” is the catch. The more common .init() panics if a subscriber already exists:

Unable to install global subscriber: SetGlobalDefaultError("a global default trace dispatcher has already been set")

In production the startup code runs once, so it never happens. In tests it does: several tests start the service in the same process, and the second one panics for a reason unrelated to what it tests. .try_init() returns an error instead, and .ok() drops it on purpose. In my code a comment next to it says why: it can only fail when a subscriber is already there, and the one already there is fine.

A fixed message for what happened, fields for why

tracing events take fields as well as a message. I use a short, fixed message that says what happened, and put the variable parts in fields:

tracing::info!(port = config.listen_port, "listening");

tracing::warn!(error = %e, "database not ready");

The % records the value with its Display format, the readable one. This is what the demo service wrote when I paused its database:

{"timestamp":"2026-10-06T19:51:23.272933Z","level":"INFO","fields":{"message":"listening","port":18080},"target":"notes_api"}
{"timestamp":"2026-10-06T19:51:26.454268Z","level":"WARN","fields":{"message":"database not ready","error":"pool timed out while waiting for an open connection"},"target":"notes_api"}

Because the message never changes, counting how often the database wasn’t ready is a filter on one exact string, not a search across every way an error can be phrased. The port is a number, so a log tool can compare it. And target, filled in by tracing itself, says which module wrote the line.

JSON has a security benefit I didn’t expect. In plain text, a message containing a newline can fake a whole extra log line, which is called log injection. In JSON the newline is escaped inside the string, so one line is always one event.

The readiness handler is where the warning lives, inside the closure of map_err, which is the only code that runs on the error path and can see the error:

.map_err(|e| {
    tracing::warn!(error = %e, "database not ready");
    StatusCode::SERVICE_UNAVAILABLE
})?;

My first attempt put only the warn! in the closure and lost the ? along the way. A closure returns its last expression, and warn! returns nothing, so the error became () instead of a 503. With no ?, that Result was dropped, and the handler went back to answering 200. The test for the empty 503 caught it within a second.

Log once, where the error stops

Not every error deserves a log line, and none deserves three. The rule I follow is “log or return, not both”. An error that travels up with ? isn’t logged on the way, because each layer would add the same line again. It’s logged once, by whoever decides what to do with it. In the readiness handler that’s right there: the error stops travelling and becomes a 503.

Then a distinction by who caused it:

  • Client errors (bad input, not found, not authorized) are normal. Logging them as warnings fills the log with noise, and lets anyone who sends bad requests fill it on purpose. At most they go to debug.
  • Server errors (a dependency down, a bug) are logged with their cause, as warn or error.

And one rule with no exceptions: no passwords, tokens or personal data in any event. I searched every line the demo wrote for the database password. It wasn’t there, and the next post that touches logging will search again.

Logs are written for machines first

A person reads a log line once, when something is already wrong. A program reads every line, all the time, and decides whether a person gets woken up. So I write events for the program: a message that never changes, fields with names, the level that matches who has to act. Readability for humans comes from the tools that read the JSON. What I haven’t decided yet is how to log errors that happen before the subscriber exists, like a broken config file. Today they go to stderr as plain text, which is right for a person and wrong for a log collector.

The separation between these technical logs and an audit trail of who did what is a different problem, and I wrote about it in the GDPR logging post.

References