Skip to main content

millis_since_init/
millis_since_init.rs

1/*!
2Including the milliseconds elapsed since the logger was initialized in each
3record, similar to `Log4J`'s relative time pattern.
4
5Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`:
6
7```no_run,shell
8$ export MY_LOG_LEVEL='info'
9```
10*/
11
12use std::io::Write;
13use std::time::{Duration, Instant};
14
15use env_logger::{Builder, Env};
16
17fn init_logger() {
18    let env = Env::default().filter("MY_LOG_LEVEL");
19
20    let start = Instant::now();
21    Builder::from_env(env)
22        .format(move |buf, record| {
23            let elapsed = start.elapsed().as_millis();
24            writeln!(
25                buf,
26                "[{elapsed:>6} ms] {}: {}",
27                record.level(),
28                record.args()
29            )
30        })
31        .init();
32}
33
34fn main() {
35    init_logger();
36
37    log::info!("a log from `MyLogger`");
38    std::thread::sleep(Duration::from_millis(250));
39    log::warn!("another log, a moment later");
40}