skip to content

After a Rust payment service adds `tracing_subscriber::fmt().init()` beside its existing `env_logger::init()`, startup panics with `SetLoggerError`; why, and how should the subscriber be assembled?

level: seniorimportance: should knowfreq 35%

answer

  1. two claimants for one slot
  2. init also installs LogTracer
  3. drop env_logger entirely
  4. registry plus layers
  5. the builder ignores RUST_LOG

basics

~20 s

With tracing-subscriber's default tracing-log feature, init() also installs LogTracer as the log crate's global logger, a slot env_logger already holds, so it panics. Remove env_logger: LogTracer turns log records into tracing events, and one registry with filtered layers handles all output.

solid answer

~40 s

`tracing_subscriber::fmt().init()` sets the global tracing dispatcher and then, because the `tracing-log` feature is on by default, installs `tracing_log::LogTracer` as the `log` crate's logger. `env_logger::init()` already filled that once-only slot, so the second step fails and `init()` panics with "Unable to install global subscriber: SetLoggerError(())". The fix is to remove `env_logger`: `LogTracer` converts every `log` record, including those from dependencies, into a tracing event attached to the current span. Then assemble one subscriber: `tracing_subscriber::registry()` plus layers, for example a console `fmt::layer()` filtered by `EnvFilter::from_default_env()` and a `fmt::layer().json()` filtered at `LevelFilter::INFO`. Watch the defaults: the `fmt()` builder filters at `INFO` and ignores `RUST_LOG` unless you add `with_env_filter`, and `EnvFilter::from_default_env()` enables only `ERROR` when `RUST_LOG` is unset.

code

rust · 4 lines
rust
fn main() {
    env_logger::init();
    tracing_subscriber::fmt().init();
}

go deeper

for a junior

Recall that a process gets one tracing subscriber and one log logger, both installed once in main, and that tracing-subscriber can take log records too.

for a middle

Explain why init() also claims the log slot through LogTracer, why the fmt() builder ignores RUST_LOG, and what EnvFilter enables when the variable is unset.

for a senior

Diagnose the SetLoggerError panic, remove the second logger, and build a registry whose layers each carry an explicit filter, with dependencies' log records landing inside your spans.

for a principal

Own one subscriber setup per binary, shared as a small crate or function, so every service gets the same layers, defaults and JSON shape instead of a hand-rolled init each time.

## Two crates, one `log` slot A `tracing` **subscriber** collects spans and events and decides where they go; `tracing-subscriber` provides the standard ones. The `log` crate has a separate global: a logger slot that can be filled **once**. `tracing_subscriber::fmt().init()` does two things, in this order (from `SubscriberInitExt::try_init`): 1. it sets the subscriber as the global tracing default with `set_global_default`; 2. if the **`tracing-log`** feature is enabled, which it is by default, it installs `tracing_log::LogTracer` as the `log` crate's logger, with the subscriber's maximum level as `log`'s maximum level. `env_logger::init()` has already taken the `log` slot, so step 2 returns `SetLoggerError` and `init()` panics: ```plaintext thread 'main' panicked at .../tracing-subscriber-0.3.23/src/fmt/mod.rs:520:14: Unable to install global subscriber: SetLoggerError(()) ``` Swapping the order only moves the panic: `env_logger::init()` would then panic with "env_logger::init should not be called after logger initialized". ## Remove env_logger and bridge `log` Running both would also be the wrong design: `log` lines would go to one formatter and `tracing` events to another, with no shared context. **`LogTracer`** is the bridge: it is a `log::Log` implementation that turns each `log::Record` into a tracing event, attached to the span that is current when the record is logged. Dependencies still on `log` therefore show up inside your request and job spans. Its documented limit is that it does **not** turn a record's format arguments into structured fields; they stay in the message text. What survives the bridge is visible in the JSON layer's output for a bridged `log::info!` (abridged): ```plaintext {"level":"INFO","fields":{"message":"settling batch 7","log.target":"settlement","log.module_path":"settlement","log.file":"src/bin/settlement.rs","log.line":5},"target":"settlement","span":{"batch":7,"name":"settlement_job"},...} ``` - the **level** and the **target** carry over, so `EnvFilter` directives for a dependency's target still apply; - the module path, file and line arrive as `log.module_path`, `log.file` and `log.line` fields; - the formatted text becomes the `message` field, with the batch number inside the text rather than a field of its own; - the event sits inside the current span, here `settlement_job{batch=7}`. The reverse bridge exists too: `tracing`'s optional `log` feature makes events emit `log` records when no tracing subscriber is installed, intended for libraries whose users might run either. Combining a `log`-to-`tracing` adapter with `tracing`'s `log-always` feature duplicates events, and the tracing-log docs warn that mixing the two directions can make records recurse. ## Assembling one subscriber `tracing_subscriber::registry()` returns a **`Registry`**, which stores span data; **layers** added with `.with(...)` observe that data and produce output. A filter can be **global** (a filter layer that disables data for the whole stack) or **per-layer** (`Layer::with_filter`, which requires the crate's `registry` feature, on by default through `fmt`). ```rust let console = fmt::layer() .with_writer(std::io::stderr) .with_filter(EnvFilter::from_default_env()); let json = fmt::layer() .json() .with_writer(std::io::stdout) .with_filter(LevelFilter::INFO); tracing_subscriber::registry().with(console).with(json).init(); ``` Here the console follows `RUST_LOG` while the JSON stream stays at `INFO`, independently. `EnvFilter` needs the `env-filter` feature and JSON needs the `json` feature; neither is on by default. ## Defaults that change what you see | Construction | Filter when `RUST_LOG` is unset | Reads `RUST_LOG`? | |---|---|---| | `tracing_subscriber::fmt().init()` (the builder) | `INFO` | no | | `tracing_subscriber::fmt::init()`, `env-filter` off | `INFO` | yes, through a `Targets` filter | | `tracing_subscriber::fmt::init()`, `env-filter` on | `ERROR` | yes, through `EnvFilter` | | `EnvFilter::from_default_env()` in a layer | `ERROR` | yes | So a service that switches from `fmt::init()` to `.with_env_filter(EnvFilter::from_default_env())` and runs without `RUST_LOG` suddenly loses its info lines. `EnvFilter::builder().with_default_directive(LevelFilter::INFO.into()).from_env_lossy()` sets a friendlier default. `EnvFilter` directives also go beyond `env_logger`'s: `target[span{field=value}]=level`, so `RUST_LOG='info,[{order_id=43}]=debug'` turns on debug output only inside spans with that field value. ## Checklist for the migration - Delete the `env_logger` dependency and its `init()` call. - Keep `tracing-subscriber`'s default `tracing-log` feature so dependencies' `log` records arrive. - Build one registry in `main`; call `init()` exactly once, before spawning anything. - Give every layer an explicit filter, and set a default directive for `EnvFilter`. - Turn on `fmt::format::FmtSpan::CLOSE` with `with_span_events` if you want a line with `time.busy` and `time.idle` when each span closes.

  • With the two-layer registry above and `RUST_LOG=debug`, a dependency's `log::debug!` line shows on the console but not in the JSON stream. Is that a bug?
    No. Each layer has its own filter: the console layer's `EnvFilter` allows `DEBUG`, the JSON layer's `LevelFilter::INFO` does not. `LogTracer` forwarded the record because the subscriber as a whole is interested in `DEBUG`; per-layer filtering then decides which outputs record it. A global filter layer would have removed it from both.
  • How do you stop a noisy dependency's `log` output without touching your own levels?
    Add a directive for its target to the filter, for example `RUST_LOG='info,<dependency>=warn'` with the crate's name, since bridged records keep their `log` target. `LogTracer::builder().ignore_crate("name")` drops a crate's records before conversion, but `init()` already installs a default `LogTracer`, so that route means initialising with `set_global_default` and your own `LogTracer` instead.

  • env_logger and a tracing fmt subscriber can both be installed if you order them right.
  • tracing_subscriber::fmt().init() reads RUST_LOG on its own.
  • EnvFilter::from_default_env() shows INFO when RUST_LOG is unset.
  • LogTracer turns format arguments of log records into structured fields.
  • A filter on one layer caps every other layer too.