In Rust, why does a background job's `log::info!` print nothing until `env_logger::init()` runs, and how does `RUST_LOG` decide what appears?
answer
- a facade, not a logger
- one global slot, filled once
- no-op until main installs one
- unset means errors only
basics
~20 sThe log crate is only a facade: until the binary installs a logger, every macro call goes to a built-in no-op logger and is dropped. env_logger::init() installs one that writes to stderr and filters by RUST_LOG, showing only errors when it is unset.
solid answer
~40 sThe `log` crate defines the five macros (`error!`, `warn!`, `info!`, `debug!`, `trace!`) and one process-wide logger slot that starts out holding a no-op implementation, so anything logged before a logger is installed is ignored. A binary fills that slot once, early in `main`, with an implementation such as `env_logger`: `env_logger::init()` calls `log::set_boxed_logger` and `log::set_max_level`, and panics if a logger is already installed. `env_logger` writes to stderr and reads `RUST_LOG`: unset means only `error` records, `info` enables info and above everywhere, and `job=debug` enables debug for every target whose name starts with `job`; a record's target defaults to its module path. Library crates depend only on `log` and never install a logger, because the slot can be filled only once and the application must choose.
code
rust · 14 linesuse log::{debug, error, info, warn};
fn reconcile_settlements(batch: u32) {
info!("reconciling batch {batch}");
debug!("fetched 120 settlement rows");
warn!("3 rows have no matching charge");
error!("batch {batch} left 3 rows unmatched");
}
fn main() {
reconcile_settlements(7); // before init: dropped by the no-op logger
env_logger::init();
reconcile_settlements(8);
}go deeper
Know that the log crate only provides macros and that nothing prints until main installs a logger such as env_logger. Know that RUST_LOG=info turns on info output.
Explain the global logger slot, set_logger and set_max_level, why init() panics the second time, and how RUST_LOG directives match targets by prefix.
Show the library-versus-binary rule in practice: libraries depend only on the facade, the binary initialises one logger first thing in main, and filtering is changed at run time rather than in code.
Treat the logger choice as an application-level decision: one implementation per process, a documented RUST_LOG default for each environment, and no crate in the workspace allowed to install its own.
## A facade with a no-op default The **`log` crate** is a *logging facade*: it gives every crate the same macros, `error!`, `warn!`, `info!`, `debug!` and `trace!`, but it does not decide where a record goes. That decision belongs to a **logger**, a type implementing the `log::Log` trait, installed once per process in a global slot. Until something fills that slot, it holds a built-in **no-op logger**. The crate's own documentation says the overhead in that state is very small (an integer load, comparison and jump), and that messages logged before an implementation is initialised are ignored. That is why a background job can call `log::info!` all day and print nothing: no logger, no output. Nothing is buffered for later. Two global values sit behind every macro call: - the **logger** itself, set by `log::set_logger` (a `&'static dyn Log`) or `log::set_boxed_logger` (a `Box<dyn Log>`, behind the crate's `alloc` feature); either returns `SetLoggerError` if a logger is already set; - the **maximum level**, set by `log::set_max_level`. It starts at `LevelFilter::Off`, and the macros check it before building a record, so a hand-written logger that never calls `set_max_level` receives nothing at all. ## Installing env_logger `env_logger` is one ready-made logger. Calling `env_logger::init()` early in `main` builds a logger from the environment, installs it with `set_boxed_logger` and sets the global maximum level to the most verbose level its filter allows. It **panics** if a logger is already installed (`try_init()` returns the error instead). Output goes to **stderr** by default. ```rust use log::{debug, error, info, warn}; fn reconcile_settlements(batch: u32) { info!("reconciling batch {batch}"); debug!("fetched 120 settlement rows"); warn!("3 rows have no matching charge"); error!("batch {batch} left 3 rows unmatched"); } fn main() { reconcile_settlements(7); // before init: dropped by the no-op logger env_logger::init(); reconcile_settlements(8); } ``` Run without `RUST_LOG`, only `batch 8 left 3 rows unmatched` appears: batch 7 ran before the logger existed, and batch 8's info, debug and warn lines are below the default filter. ## How RUST_LOG filters `RUST_LOG` is a comma-separated list of **directives**, each `target=level`, just a `level`, or just a `target`. A record's **target** defaults to the module path of the call site, rooted at the crate name, and a directive matches by **prefix**, so `job` also matches `job::db`, and even `jobs`, as a plain string prefix (the env_logger docs show `example` matching `examples::and_more_examples`). | `RUST_LOG` | What the job prints | |---|---| | unset | only `error` records (env_logger's default) | | `info` | info, warn and error from every target | | `job=debug` | debug and above from targets starting with `job`, nothing from other crates | | `warn,job=debug` | warn and above everywhere, debug and above for `job` | | `off` | nothing | Level names are case-insensitive. To default to something other than errors when the variable is unset, build the logger with `env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn")).init()`. ## Targets and expensive arguments Every macro accepts an explicit target, `info!(target: "settlement_audit", "...")`, which lets a directive such as `RUST_LOG=settlement_audit=info` select one stream of records regardless of the module that wrote it. The level check happens before the message is formatted, so a disabled `debug!` costs only that comparison. When building the data for a message is itself expensive, guard it with `log::log_enabled!(log::Level::Debug)`, which checks the static and global maximum levels and then asks the installed logger whether that level and target are enabled, and do the work only when the answer is yes. ## Libraries never install a logger The `log` documentation draws the line explicitly: **libraries link only to `log`** and use its macros; **executables choose an implementation** and initialise it early. The logger slot is process-wide and can be set only once, so a library that called `env_logger::init()` would take that choice away from every application using it, and the application's own `init()` would then panic. The order of work in a binary: 1. Add `log` and one logger implementation, such as `env_logger`, as dependencies. 2. Call the logger's `init()` as the first thing in `main`, before spawning workers. 3. Log with the `log` macros everywhere, in the binary and its libraries alike. 4. Control verbosity at run time with `RUST_LOG`, not by editing code. ## Common mistakes - Expecting `log::info!` to behave like `println!`: without a logger it prints nothing. - Expecting info lines with `RUST_LOG` unset: env_logger shows errors only by default. - Writing arguments with side effects inside a log macro: the docs warn they may not be evaluated when the level is disabled. - Calling `init()` from more than one place: the second call panics.
- You implement `log::Log` yourself and call `log::set_logger(&LOGGER)`, yet even `error!` prints nothing. Why?The global maximum level starts at `LevelFilter::Off`, and the macros compare against it before they build a record, so your logger is never called. An implementation must also call `log::set_max_level`, for example `log::set_max_level(LevelFilter::Info)`, right after installing itself. `env_logger` does this for you inside `init()`.
- How do you make env_logger default to `warn` when `RUST_LOG` is not set, while still letting the variable override it?Build the logger from an `Env` with a fallback: `env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn")).init();`. If `RUST_LOG` is present its directives win; if it is absent the filter behaves as if it were `warn`.
The log crate is a wall socket standard: every appliance (library) can plug into it, but no power flows until the building (the binary) connects one supply (the logger), and only one supply can be connected.
- log::info! prints to stdout by itself, like println!.
- A library crate should call env_logger::init() so its own logs appear.
- With RUST_LOG unset, env_logger shows info and above.
- Records logged before init() are buffered and printed once the logger starts.
- Calling env_logger::init() a second time just reconfigures the logger.