skip to content

A Rust deploy tool logs each anyhow error at every layer before returning it with ?; why is that worse, and where should it log?

level: seniorimportance: should knowfreq 40%

answer

  1. one failure, many lines
  2. each line misses the root cause
  3. context travels inside the Err
  4. the layer that handles it

basics

~20 s

Logging and then returning with ? writes one fragment per layer, often with {} so the root cause never appears. Lower layers should only add context and propagate; the boundary that handles the error logs it once, with {:#} or {:?}.

solid answer

~40 s

Each layer logs before its callers have added their context, so one missing manifest becomes several lines, some identical, and with `{}` none of them shows `No such file or directory (os error 2)`, because `{}` prints only an `anyhow::Error`'s outermost layer. Error counts inflate and no line tells the whole story. In Rust the `Err` value carries the context upward, so lower layers should call `.with_context(...)` and return with `?`. The place that consumes the error, such as `main`, the request handler, the job loop or a retry decision, logs once with `{:#}` for one line or `{:?}` for the full report. A layer that swallows an error, by retrying or falling back, is itself that boundary and logs there.

code

rust · 21 lines
rust
use anyhow::{Context, Result};
use std::fs;

fn read_manifest(path: &str) -> Result<String> {
    fs::read_to_string(path)
        .with_context(|| format!("failed to read {path}"))
        .inspect_err(|e| eprintln!("ERROR {e}"))
}

fn plan_release(env: &str) -> Result<()> {
    read_manifest(&format!("deploy/{env}.toml"))
        .with_context(|| format!("cannot plan release for {env}"))
        .inspect_err(|e| eprintln!("ERROR {e}"))?;
    Ok(())
}

fn main() {
    if let Err(e) = plan_release("prod") {
        eprintln!("ERROR {e}");
    }
}

go deeper

for a junior

Recall the rule of thumb: either handle an error or return it, but do not log it and then return it as well.

for a middle

Explain that the Err value carries context upward, that {} hides lower causes, and that the boundary logs once with {:#} or {:?}.

for a senior

Identify the real boundaries in a codebase, including swallowed retries, unjoined threads and type conversions, and make sure each logs exactly once with the full chain.

for a principal

Weigh one complete line per failure against per-layer breadcrumbs, and decide where the team relies on error context versus tracing spans for the path.

## The anti-pattern A layered deploy tool often grows code like this: each function logs the error and then returns it with `?`, "just in case". With anyhow and an `inspect_err` that prints at two inner layers and once more in `main`, a single missing manifest produces: ```plaintext ERROR failed to read deploy/prod.toml ERROR cannot plan release for prod ERROR cannot plan release for prod ``` Three lines for one failure, two of them identical, and **none of them contains the root cause** `No such file or directory (os error 2)`, because each was printed with `{}`, which shows only the outermost layer of an `anyhow::Error`. ## Why it is worse than it looks - **Volume and noise.** One failure becomes N log lines, where N is the depth of the call stack. Alert rules that count error lines over-count, and the real incident is buried among copies. - **Fragments, not a story.** Each line is written before the layers above have added their context, so no single line has the whole picture. Reconstructing it means correlating lines by timestamp. - **Lost root cause.** Lines written with `{}` miss every cause below the first layer, which is precisely the part an operator needs. - **Wrong decisions encoded low down.** A low layer cannot know whether the error is fatal, will be retried, or is expected (a missing optional file). Logging it as `ERROR` there is a guess. ## The rule: add context while propagating, log once where the error is handled In Rust, an `Err` is an ordinary value that travels up through `?`. The function that **consumes** it, by stopping, retrying, falling back or turning it into a response, is the only place that knows what the failure means. So: 1. **Lower layers** attach context with `.context(...)` or `.with_context(|| ...)` from the `anyhow::Context` trait and return the error. They do not log. 2. **The boundary** (`main`, the per-request handler, the job loop, the place where a retry decision is made) logs the error **once**, with a format that shows the whole chain. 3. **A layer that swallows an error** (it retries and succeeds, or falls back to a default) is itself a boundary for that error and logs there, usually at a lower level, because nothing above will ever see it. ## Choosing the format at the boundary | Format | What the log line contains | Fits | |---|---|---| | `{}` | outermost message only | almost never for an error log | | `{:#}` | all layers on one line, separated by `: ` | line-oriented logs, a single structured field | | `{:?}` | multi-line report with `Caused by:` and a backtrace if captured | stderr of a CLI, a detailed log entry | | `err.chain()` | each cause separately | structured logs that want causes as a list field | With the boundary-only version, the same failure produces one line per deployment: `deploy prod failed: cannot plan release for prod: failed to read deploy/prod.toml: No such file or directory (os error 2)`. ## Where the logging crates fit The macro that writes the line (`eprintln!`, the `log` facade's `error!`, or a `tracing` event) does not change the rule; those crates, and attaching causes to spans, are covered with logging and tracing. The Rust-specific parts are that context travels inside the error value, that `{:#}` and `{:?}` render it, and that `?` makes "return without logging" the shortest code path. ## Exceptions worth defending - **Crossing a boundary that drops the error.** A thread or task whose result nobody joins, or a callback whose return value is ignored, must log before the error disappears. - **Converting to a different error type.** When a layer maps an `anyhow::Error` into a typed error for an external API and discards the chain, it should log the full chain once at that point. - **Security-sensitive detail.** The boundary may log the full `{:?}` internally while returning only `{}` to an untrusted client. ## What a reviewer looks for - `log`-then-`?` or `inspect_err` that prints and then propagates in non-boundary code. - Error logs written with `{}` on an `anyhow::Error`. - Context messages that repeat the cause (`"... : {e}"`), which duplicates text once `{:#}` prints the chain.

  • When must a lower layer log an error itself?
    When the error will not reach anyone above: a retry that eventually succeeds, a fallback to a default, a spawned thread or task whose result is never joined, or a conversion to a typed error that discards the chain. That layer has become the boundary for this error, so it logs it once there.
  • Which format should the boundary use for a line-oriented log?
    `{:#}`, which writes every layer of the `anyhow::Error` on one line separated by `: `. `{:?}` is multi-line and may include a backtrace, which suits a CLI's stderr; `err.chain()` suits structured logs that want each cause as a separate field.

  • Logging at every layer is safer because the error might get lost on the way up.
  • Writing each log line with {} is enough because the message names the failure.
  • A low-level function knows best whether its failure is an ERROR.
  • A retry loop that recovers never needs to log the failures it absorbed.
  • Once the boundary logs the error, lower layers need no context messages.