]>
Commit | Line | Data |
---|---|---|
e74abb32 XL |
1 | /*! |
2 | Changing the default logging format. | |
3 | ||
4 | Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`: | |
5 | ||
6 | ```no_run,shell | |
7 | $ export MY_LOG_LEVEL='info' | |
8 | ``` | |
9 | ||
10 | Also try setting the `MY_LOG_STYLE` environment variable to `never` to disable colors | |
11 | or `auto` to enable them: | |
12 | ||
13 | ```no_run,shell | |
14 | $ export MY_LOG_STYLE=never | |
15 | ``` | |
16 | ||
17 | If you want to control the logging output completely, see the `custom_logger` example. | |
18 | */ | |
19 | ||
20 | #[macro_use] | |
21 | extern crate log; | |
22 | extern crate env_logger; | |
23 | ||
24 | use std::io::Write; | |
25 | ||
26 | use env_logger::{Env, Builder, fmt}; | |
27 | ||
28 | fn init_logger() { | |
29 | let env = Env::default() | |
30 | .filter("MY_LOG_LEVEL") | |
31 | .write_style("MY_LOG_STYLE"); | |
32 | ||
33 | let mut builder = Builder::from_env(env); | |
34 | ||
35 | // Use a different format for writing log records | |
36 | // The colors are only available when the `termcolor` dependency is (which it is by default) | |
37 | #[cfg(feature = "termcolor")] | |
38 | builder.format(|buf, record| { | |
39 | let mut style = buf.style(); | |
40 | style.set_bg(fmt::Color::Yellow).set_bold(true); | |
41 | ||
42 | let timestamp = buf.timestamp(); | |
43 | ||
44 | writeln!(buf, "My formatted log ({}): {}", timestamp, style.value(record.args())) | |
45 | }); | |
46 | ||
47 | builder.init(); | |
48 | } | |
49 | ||
50 | fn main() { | |
51 | init_logger(); | |
52 | ||
53 | info!("a log from `MyLogger`"); | |
54 | } |