summary refs log tree commit diff stats
path: root/src/logging.rs
blob: 7b8bd2e844b0d23ec3dd2f35d1df17d1149f01a1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } 
use std::fs;
use std::fs::File;

use chrono::offset::Utc;
use simplelog::*;
use users;

lazy_static! {
    static ref FILE: String = format!(
        "/tmp/clinte_{}.log",
        users::get_current_username()
            .unwrap()
            .into_string()
            .unwrap()
    );
}

pub fn init() {
    // If the log file exists on startup,
    // move and timestamp it so we get a
    // fresh log file.
    if fs::metadata(FILE.clone()).is_ok() {
        let mut new_file = FILE.clone();
        let time = Utc::now().to_rfc3339();
        new_file.push_str(".");
        new_file.push_str(&time);
        fs::rename(FILE.clone(), new_file).unwrap();
    }

    CombinedLogger::init(vec![
        TermLogger::new(LevelFilter::Warn, Config::default(), TerminalMode::Stderr).unwrap(),
        WriteLogger::new(
            LevelFilter::Info,
            Config::default(),
            File::create(FILE.clone()).unwrap(),
        ),
    ])
    .expect("Unable to initialize logging");
}

#[cfg(test)]
mod tests {
    use super::*;

    use log::info;

    #[test]
    fn init_logs() {
        let blank = " ".bytes().collect::<Vec<u8>>();
        fs::write("/tmp/clinte.log", &blank).unwrap();
        init();

        info!("TEST LOG MESSAGE");
        let logfile = fs::read_to_string("/tmp/clinte.log").unwrap();
        assert!(logfile.contains("TEST LOG MESSAGE"));
    }
}