skip to content

In Rust, what decides whether std::backtrace::Backtrace::capture records a stack, and how do RUST_BACKTRACE and RUST_LIB_BACKTRACE differ?

level: middleimportance: must knowfreq 50%

answer

  1. two environment variables, one priority
  2. the value 0 means off
  3. read once, then cached
  4. panics read only one of them

basics

~20 s

Backtrace::capture checks RUST_LIB_BACKTRACE first, then RUST_BACKTRACE; a value of 0 disables it, any other value enables it, and neither set means disabled. The default panic hook reads only RUST_BACKTRACE, so RUST_LIB_BACKTRACE controls error backtraces separately.

solid answer

~30 s

`std::backtrace::Backtrace`, stable since Rust 1.65, has `capture()`, which obeys the environment, and `force_capture()`, which ignores it. `capture()` uses `RUST_LIB_BACKTRACE` if it is set (`0` off, anything else on); otherwise it uses `RUST_BACKTRACE` by the same rule; with neither set it returns a backtrace whose `status()` is `Disabled`. The decision is cached on the first `capture()` call. The default panic output reads only `RUST_BACKTRACE`, so `RUST_BACKTRACE=1 RUST_LIB_BACKTRACE=0` gives panic traces without paying for error traces, and `RUST_LIB_BACKTRACE=1` gives error traces only. anyhow calls `capture()` when an error first becomes an `anyhow::Error`, and prints the result in its `{:?}` form.

code

rust · 13 lines
rust
use std::backtrace::Backtrace;

fn main() {
    // Governed by RUST_LIB_BACKTRACE, then RUST_BACKTRACE.
    println!("capture:       {:?}", Backtrace::capture().status());
    // Ignores both variables.
    println!("force_capture: {:?}", Backtrace::force_capture().status());

    // The variables are read once and cached, so this change is ignored.
    // set_var is an unsafe fn on edition 2024.
    unsafe { std::env::set_var("RUST_LIB_BACKTRACE", "1") };
    println!("after set_var: {:?}", Backtrace::capture().status());
}

go deeper

for a junior

Recall that RUST_BACKTRACE=1 shows a backtrace when a program panics, and that error backtraces need an environment variable too.

for a middle

Explain the lookup order, RUST_LIB_BACKTRACE then RUST_BACKTRACE, the meaning of 0, the cached decision, force_capture, and the status() values.

for a senior

Diagnose the cost: capture happens per error constructed, symbolisation at print time, so enabling RUST_BACKTRACE in a busy service can slow error paths unless RUST_LIB_BACKTRACE=0 is set.

for a principal

Choose an environment policy per deployment: panic traces on everywhere, error traces on only where the capture cost is acceptable or during an investigation.

## The type and when it arrived `std::backtrace::Backtrace` was stabilised in **Rust 1.65** (November 2022). It represents a captured stack of the current OS thread. Three constructors decide whether anything is recorded: - **`Backtrace::capture()`** records a stack only if the environment allows it. - **`Backtrace::force_capture()`** always records one, ignoring the environment. - **`Backtrace::disabled()`** returns an empty backtrace (it is even a `const fn`). `backtrace.status()` returns a `BacktraceStatus`: `Captured`, `Disabled` (turned off by the environment) or `Unsupported` (the platform cannot capture). The enum is `#[non_exhaustive]`, so a `match` on it needs a wildcard arm. ## The environment rules for `Backtrace::capture` The rules are written in `library/std/src/backtrace.rs` and the code that implements them is a few lines long: 1. If **`RUST_LIB_BACKTRACE`** is set, it alone decides: the value `0` disables capture, any other value enables it. 2. Otherwise, if **`RUST_BACKTRACE`** is set, it decides by the same rule. 3. If neither is set, `capture()` is disabled. The result is computed once, on the first `capture()` call, and **cached** in a static. Changing either variable afterwards, for example with `std::env::set_var` (an `unsafe fn` on edition 2024), does not change later captures. | Environment | `Backtrace::capture()` | default panic output (most targets) | |---|---|---| | neither set | `Disabled` | no backtrace, a note suggesting `RUST_BACKTRACE=1` | | `RUST_BACKTRACE=1` | `Captured` | short backtrace | | `RUST_LIB_BACKTRACE=1` | `Captured` | no backtrace | | `RUST_BACKTRACE=1 RUST_LIB_BACKTRACE=0` | `Disabled` | short backtrace | The last column is the panic side, which reads only `RUST_BACKTRACE` (`0`, `1`, or `full` for unabbreviated frames); panic hooks and their output are covered with panics. The point for errors is that **`RUST_LIB_BACKTRACE` exists so you can switch library and error backtraces independently of panic backtraces.** ## How anyhow uses it On stable Rust, anyhow calls `Backtrace::capture()` when an error first becomes an `anyhow::Error`: through `?` (its `From` impl), `anyhow::Error::new`, the `anyhow!` macro, or `context`/`with_context` on a non-anyhow error. Adding more context to something that is already an `anyhow::Error` does not capture again; the source notes that the cause already has one. The captured trace is then printed by the `{:?}` format, under `Stack backtrace:`, and `err.backtrace()` returns it. anyhow's documentation spells out the three useful settings: - panics and errors both with backtraces: `RUST_BACKTRACE=1`; - only errors: `RUST_LIB_BACKTRACE=1`; - only panics: `RUST_BACKTRACE=1` with `RUST_LIB_BACKTRACE=0`. ## What capture costs std's docs say capturing "can be both memory intensive and slow". The implementation splits the work: - **Capture** walks the stack and stores instruction pointers. This happens at `capture()` time, once per error constructed. - **Symbol resolution** (turning addresses into function names, files and lines) is deferred until the backtrace is printed, and is usually the more expensive step. So enabling capture in a process that creates many errors on a hot path, even errors that are handled and thrown away, pays the stack walk for each one. File and line numbers also need debug information in the binary; without it, frames show only symbol names or addresses. ## Reading a backtrace you captured A `Backtrace` implements both `Display` and `Debug`: - `{}` prints the short style, starting at the frame that called `capture()`, with paths shortened relative to the current directory; - `{:#}` prints every frame in the full style; - a backtrace that was never recorded prints `disabled backtrace` (or `unsupported backtrace`) rather than failing. Remember **where** the stack was taken. For an `anyhow::Error` it is the moment the error became an `anyhow::Error`, which is the `?` or the `context` call in your function, not the system call that failed inside std; by the time the `io::Error` reached your code, that deeper stack no longer existed. That is usually what you want, because it points at the line in your code, but it is also why adding context close to the failing call gives a more useful trace than converting only at the top. ## Practical consequences - A CLI that wants error backtraces only when debugging can leave both variables unset by default and document `RUST_LIB_BACKTRACE=1`. - A long-running service that turned on `RUST_BACKTRACE=1` to see panic traces also turned on error capture; set `RUST_LIB_BACKTRACE=0` beside it to keep panics only. - A test or diagnostic that must always have a trace calls `force_capture()` explicitly. - Code that inspects the result checks `status()` rather than assuming a printed trace is non-empty.

  • A service set `RUST_BACKTRACE=1` to see panic traces and its error-heavy endpoints got slower. Why, and what is the fix?
    With `RUST_LIB_BACKTRACE` unset, `Backtrace::capture()` falls back to `RUST_BACKTRACE`, so every `anyhow::Error` created now walks the stack, even errors that are handled and dropped. Setting `RUST_LIB_BACKTRACE=0` beside it keeps panic backtraces and disables error capture.
  • Why might setting `RUST_LIB_BACKTRACE` from inside the program have no effect?
    std reads the two variables once, on the first `Backtrace::capture()` call, and caches the decision in a static. Later changes through `std::env::set_var` are ignored. A program that must always capture calls `Backtrace::force_capture()` instead.
  • What does capture cost compared with printing?
    Capture walks the stack and stores instruction pointers when `capture()` runs. Symbol resolution, turning addresses into names, files and lines, is deferred until the backtrace is printed and is usually the more expensive step. File and line numbers also need debug information in the binary.

  • RUST_BACKTRACE controls only panics, never Backtrace::capture.
  • Backtrace::capture always records a stack; the variables only affect printing.
  • Setting RUST_LIB_BACKTRACE with set_var at run time switches capture on immediately.
  • RUST_LIB_BACKTRACE=0 also turns off the default panic backtrace.
  • Every context layer added to an anyhow::Error captures a fresh backtrace.

Assumes Rust 1.99; std::backtrace::Backtrace and its environment rules have been stable since Rust 1.65.