pretty_flexible_env_logger/
lib.rs

1#![cfg_attr(test, deny(warnings))]
2#![deny(missing_docs)]
3#![doc(html_root_url = "https://docs.rs/pretty_flexible_env_logger/latest/")]
4
5//! A logger configured via run-time value or one taken from an environment variable which
6//! writes to standard error with nice colored output for log levels.
7//!
8//! ## Example
9//!
10//! ```
11//! use log::{debug,info,warn,error};
12//! use std::env;
13//!
14//! fn main() {
15//!     let args: Vec<String> = env::args().collect();
16//!     let default = "RUST_LOG".to_string();
17//!     let level = args.get(1).unwrap_or(&default);
18//!     if let Err(e) = pretty_flexible_env_logger::try_init_with(level) {
19//!         eprintln!("Some custom msg {}", e);
20//!         panic!("error!") // or whatever
21//!     }
22//!     
23//!     info!("info");
24//!     warn!("warn");
25//!     error!("error");
26//!     debug!("debug");
27//! }
28//! ```
29//!
30//! ## Defaults
31//!
32//! The defaults can be setup by calling [init()][init] or [try_init()][try_init] at the start
33//! of the program.
34//!
35//! ## Enable logging
36//!
37//! This crate uses [pretty_env_logger][] internally, so the same ways of enabling
38//! logs through an environment variable are supported.
39//!
40//! [env_logger]: https://docs.rs/env_logger
41//! [pretty_env_logger]: https://docs.rs/pretty_env_logger
42//! [init]: [pretty_flexible_env_logger::init]
43//! [try_init]: [pretty_flexible_env_logger::try_init]
44
45#[doc(hidden)]
46pub use pretty_env_logger;
47
48#[doc(hidden)]
49pub use pretty_env_logger::env_logger;
50
51use log::SetLoggerError;
52use pretty_env_logger::{formatted_builder, formatted_timed_builder};
53
54/// Initializes default global logger.
55///
56/// This should be called early in the execution of a Rust program, and the
57/// global logger may only be initialized once. Future initialization attempts
58/// will return an error.
59///
60/// It defaults to using settings from `RUST_LOG` environment variable
61///
62/// # Panics
63///
64/// This function fails to set the global logger if one has already been set.
65pub fn init() {
66    init_with("RUST_LOG");
67}
68
69/// Initializes default global logger with timed entries.
70///
71/// This should be called early in the execution of a Rust program, and the
72/// global logger may only be initialized once. Future initialization attempts
73/// will return an error.
74///
75/// It defaults to using settings from `RUST_LOG` environment variable
76///
77/// # Panics
78///
79/// This function fails to set the global logger if one has already been set.
80pub fn init_timed() {
81    init_timed_with("RUST_LOG");
82}
83
84/// Tries to initialize default global logger.
85///
86/// This should be called early in the execution of a Rust program, and the
87/// global logger may only be initialized once. Future initialization attempts
88/// will return an error.
89///
90/// # Errors
91///
92/// This function fails to set the global logger if one has already been set.
93pub fn try_init() -> Result<(), SetLoggerError> {
94    try_init_with("RUST_LOG")
95}
96
97/// Tries to initialize default global logger with timed entries.
98///
99/// This should be called early in the execution of a Rust program, and the
100/// global logger may only be initialized once. Future initialization attempts
101/// will return an error.
102///
103/// # Errors
104///
105/// This function fails to set the global logger if one has already been set.
106pub fn try_init_timed() -> Result<(), SetLoggerError> {
107    try_init_timed_with("RUST_LOG")
108}
109
110/// Initializes the global logger with a custom configuration.
111///
112/// This should be called early in the execution of a Rust program, and the
113/// global logger may only be initialized once. Future initialization attempts
114/// will return an error.
115///
116/// # Arguments
117///
118/// * `environment_or_inline_value` - A string slice that holds the name of environment variable, or
119///    the directives string in the same form as the `RUST_LOG` environment variable.
120///
121/// # Panics
122///
123/// This function fails to set the global logger if one has already been set.
124pub fn init_with(environment_or_inline_value: &str) {
125    try_init_with(environment_or_inline_value).unwrap();
126}
127
128/// Initializes the timed global logger with a custom configuration.
129///
130/// This should be called early in the execution of a Rust program, and the
131/// global logger may only be initialized once. Future initialization attempts
132/// will return an error.
133///
134/// # Arguments
135///
136/// * `environment_or_inline_value` - A string slice that holds the name of environment variable, or
137///    the directives string in the same form as the `RUST_LOG` environment variable.
138///
139/// # Errors
140///
141/// This function fails to set the global logger if one has already been set.
142pub fn init_timed_with(environment_or_inline_value: &str) {
143    try_init_with(environment_or_inline_value).unwrap()
144}
145
146/// Tries to initialize the global logger with a custom configuration.
147///
148/// This should be called early in the execution of a Rust program, and the
149/// global logger may only be initialized once. Future initialization attempts
150/// will return an error.
151///
152/// # Arguments
153///
154/// * `environment_or_inline_value` - A string slice that holds the name of environment variable, or
155///    the directives string in the same form as the `RUST_LOG` environment variable.
156///
157/// # Errors
158///
159/// This function fails to set the global logger if one has already been set.
160pub fn try_init_with(environment_or_inline_value: &str) -> Result<(), SetLoggerError> {
161    let value = match ::std::env::var(environment_or_inline_value) {
162        Ok(s) => Some(s),
163        Err(_) => Some(environment_or_inline_value.to_string()),
164    };
165    try_init_custom_string(value)
166}
167
168/// Tries to initialize the timed global logger with a custom configuration.
169///
170/// This should be called early in the execution of a Rust program, and the
171/// global logger may only be initialized once. Future initialization attempts
172/// will return an error.
173///
174/// # Arguments
175///
176/// * `environment_or_inline_value` - A string slice that holds the name of environment variable, or
177///    the directives string in the same form as the `RUST_LOG` environment variable.
178///
179/// # Errors
180///
181/// This function fails to set the global logger if one has already been set.
182pub fn try_init_timed_with(environment_or_inline_value: &str) -> Result<(), log::SetLoggerError> {
183    let value = match ::std::env::var(environment_or_inline_value) {
184        Ok(s) => Some(s),
185        Err(_) => Some(environment_or_inline_value.to_string()),
186    };
187    try_init_timed_custom_string(value)
188}
189
190/// Tries to initialize the global logger with custom filtering directives.
191///
192/// This should be called early in the execution of a Rust program, and the
193/// global logger may only be initialized once. Future initialization attempts
194/// will return an error.
195///
196/// # Arguments
197///
198/// * `filters` - A directives `String` in the same form as the `RUST_LOG` environment variable.
199///
200/// # Errors
201///
202/// This function fails to set the global logger if one has already been set.
203pub fn try_init_custom_string(filters: Option<String>) -> Result<(), SetLoggerError> {
204    let mut builder = formatted_builder();
205
206    if let Some(s) = filters {
207        builder.parse_filters(&s);
208    }
209
210    builder.try_init()
211}
212
213/// Tries to initialize the timed global logger with custom filtering directives.
214///
215/// This should be called early in the execution of a Rust program, and the
216/// global logger may only be initialized once. Future initialization attempts
217/// will return an error.
218///
219/// # Arguments
220///
221/// * `filters` - A directives `String` in the same form as the `RUST_LOG` environment variable.
222///
223/// # Errors
224///
225/// This function fails to set the global logger if one has already been set.
226pub fn try_init_timed_custom_string(filters: Option<String>) -> Result<(), SetLoggerError> {
227    let mut builder = formatted_timed_builder();
228
229    if let Some(s) = filters {
230        builder.parse_filters(&s);
231    }
232
233    builder.try_init()
234}