tracing/tracing-log/src/env_logger.rs
Eliza Weisman 8bd4d90e78
meta: consolidate & clean up crates (#323)
## Motivation

`tracing` currently consists of a large number of crates. The number of
crates has the potential to be quite intimidating to users. 

## Solution

This branch makes the following changes:

 - Delete `tracing-fmt`. This crate's functionality has already been
   moved into `tracing-subscriber`, and a final version has been
   published to deprecate the crate & link to the code's new home.
 - Delete `tracing-tower-http`, as this functionality is now subsumed
   by `tracing-tower`. Since the crate was never published, we do not 
   need to deprecate it.
 - Delete `tracing-slog`. This crate was never implemented, so we can
   just remove it from the repository. It can be re-created if we ever
   implement `slog` integration.
 - Move `tracing-env-logger` into a `tracing-log` module, and feature 
   flag it. I updated some of the APIs as well.
 - Remove deleted crates from documentation.

This makes most of the changes discussed in #308.

Closes #308

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2019-09-04 13:20:35 -07:00

52 lines
1.7 KiB
Rust

//! Utilities for configuring the `env_logger` crate to emit `tracing` events.
use env_logger;
use log;
/// Extension trait to configure an `env_logger::Builder` to emit traces.
pub trait BuilderExt: crate::sealed::Sealed {
/// Configure the built `env_logger::Logger` to emit `tracing` events for
/// all consumed `log` records, rather than printing them to standard out.
///
/// Note that this replaces any previously configured formatting.
fn emit_traces(&mut self) -> &mut Self;
}
impl crate::sealed::Sealed for env_logger::Builder {}
impl BuilderExt for env_logger::Builder {
fn emit_traces(&mut self) -> &mut Self {
self.format(|_, record| super::format_trace(record))
}
}
/// Attempts to initialize the global logger with an env logger configured to
/// emit `tracing` events.
///
/// This should be called early in the execution of a Rust program. Any log
/// events that occur before initialization will be ignored.
///
/// # Errors
///
/// This function will fail if it is called more than once, or if another
/// library has already initialized a global logger.
pub fn try_init() -> Result<(), log::SetLoggerError> {
env_logger::Builder::from_default_env()
.emit_traces()
.try_init()
}
/// Initializes the global logger with an env logger configured to
/// emit `tracing` events.
///
/// This should be called early in the execution of a Rust program. Any log
/// events that occur before initialization will be ignored.
///
/// # Panics
///
/// This function will panic if it is called more than once, or if another
/// library has already initialized a global logger.
pub fn init() {
try_init()
.expect("tracing_log::env_logger::init should not be called after logger initialized");
}