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