tracing_log/env_logger.rs
1//! Utilities for configuring the `env_logger` crate to emit `tracing` events.
2
3/// Extension trait to configure an `env_logger::Builder` to emit traces.
4pub trait BuilderExt: crate::sealed::Sealed {
5 /// Configure the built `env_logger::Logger` to emit `tracing` events for
6 /// all consumed `log` records, rather than printing them to standard out.
7 ///
8 /// Note that this replaces any previously configured formatting.
9 fn emit_traces(&mut self) -> &mut Self;
10}
11
12impl crate::sealed::Sealed for env_logger::Builder {}
13
14impl BuilderExt for env_logger::Builder {
15 fn emit_traces(&mut self) -> &mut Self {
16 self.format(|_, record| super::format_trace(record))
17 }
18}
19
20/// Attempts to initialize the global logger with an env logger configured to
21/// emit `tracing` events.
22///
23/// This should be called early in the execution of a Rust program. Any log
24/// events that occur before initialization will be ignored.
25///
26/// # Errors
27///
28/// This function will fail if it is called more than once, or if another
29/// library has already initialized a global logger.
30pub fn try_init() -> Result<(), log::SetLoggerError> {
31 env_logger::Builder::from_default_env()
32 .emit_traces()
33 .try_init()
34}
35
36/// Initializes the global logger with an env logger configured to
37/// emit `tracing` events.
38///
39/// This should be called early in the execution of a Rust program. Any log
40/// events that occur before initialization will be ignored.
41///
42/// # Panics
43///
44/// This function will panic if it is called more than once, or if another
45/// library has already initialized a global logger.
46pub fn init() {
47 try_init()
48 .expect("tracing_log::env_logger::init should not be called after logger initialized");
49}