alto_logger/
lib.rs

1/*!
2## filtering
3Use the ENV variable `RUST_LOG` with `module_name=level`
4
5`RUST_LOG="tokio=warn,my_module=info,my_module::inner=trace"`
6
7A default level can be provided with just ***level***. e.g. `RUST_LOG=trace` will enable `trace` for all modules.
8
9You can disable specific modules/crates by using the `off` level
10
11## optional features
12* `time` allows formatting a UTC timestamp with the [`time`](time) crate.
13    * see the formatting description [here](https://time-rs.github.io/book/api/format-description.html)
14[time]: https://docs.rs/time
15*/
16
17#[cfg(all(doctest))]
18doc_comment::doctest!("../README.md");
19
20#[doc(inline)]
21pub use termcolor::Color;
22
23/// Initialize the logger
24///
25/// ```rust
26/// use alto_logger::{
27///     options::{ColorConfig, StyleConfig, TimeConfig},
28///     Options,
29///     TermLogger,
30/// };
31/// alto_logger::init(
32///     TermLogger::new(
33///         Options::default()
34///             .with_style(StyleConfig::SingleLine)     // Default is a MultiLine output
35///             .with_time(TimeConfig::relative_now())   // Default is no timestamp
36///             .with_color(ColorConfig::only_levels()), // Default is full color
37///     )
38///     .unwrap(),
39/// )
40/// .unwrap()
41/// ```
42///
43/// And using the shorthands
44/// ```rust,ignore
45/// use alto_logger::*;
46///
47/// // statically parse a format description
48/// let fmt = time::macros::format_description!("[hour]:[minute]:[second]");
49///
50/// MultiLogger::new()
51///     .with(TermLogger::default())
52///      // date_time_format requires the `time` feature
53///     .with(FileLogger::append(TimeConfig::date_time_format(format), "output.log").unwrap())
54///     .init()
55///     .expect("init logger");
56/// ```
57///
58pub fn init(logger: impl log::Log + 'static) -> Result<(), Error> {
59    // enables trace for all
60    log::set_max_level(log::LevelFilter::Trace);
61    log::set_boxed_logger(Box::new(logger)).map_err(Error::SetLogger)
62}
63
64/// Convenience function to create a default terminal logger
65///
66/// This defaults to using:
67/// * no timestamp
68/// * default colors
69/// * multi-line output
70pub fn init_term_logger() -> Result<(), Error> {
71    TermLogger::new(Options::default()).and_then(init)
72}
73
74/// Convenience function to create a terminal logger that uses a single-line output, and unix timestamps.
75pub fn init_alt_term_logger() -> Result<(), Error> {
76    TermLogger::new(
77        Options::default()
78            .with_style(StyleConfig::SingleLine)
79            .with_time(TimeConfig::unix_timestamp()),
80    )
81    .and_then(init)
82}
83
84mod error;
85mod filters;
86mod loggers;
87
88pub mod options;
89#[doc(inline)]
90pub use options::*;
91
92pub use loggers::*;
93
94#[doc(inline)]
95pub use error::Error;