hacker_news/
util.rs

1use std::io::Write;
2use env_logger::Builder;
3use log;
4use log::LevelFilter;
5use std::sync::Once;
6
7static TEST_LOGGER: Once = Once::new(); 
8
9pub fn setup() {
10    TEST_LOGGER.call_once(|| {
11        // init_logger()
12        env_logger::init();
13    });
14}
15
16
17// TODO: I want to use this custom log string writer, as it in addition to providing
18// the module path it provides you with the line of source code and file path to the
19// emitting file. However, I also really want the colorization of the log level
20// that the default log function provides. This function provides a proof of concept 
21// for how the custom log string function could still provide colorization.
22
23pub fn init_logger() {
24    let mut logger = Builder::from_default_env();
25    logger.filter(Some("hnews::html"), LevelFilter::Trace);
26    logger.format(|buf, record| {
27        
28        let timestamp = buf.timestamp();
29        let level = format!("{green}{level}{reset}", 
30            green = "\x1b[1;32m",
31            level = record.level(),
32            reset = "\x1b[1;0m",
33        );
34        let mod_path = record.module_path().unwrap_or("Could not obtain module path");
35        let file =record.file().unwrap_or("Could not obtain file");
36        let line = record.line().unwrap_or(0);
37        let args = record.args();
38
39        writeln!(
40            buf,
41            "[{timestamp} {level} {mod_path} {file}:{line}] {args}",
42            // "[{timestamp} {level} {file}:{line}] {args}",
43            timestamp = timestamp,
44            level = level,
45            mod_path = mod_path,
46            file = file,
47            line = line,
48            args = args
49        )
50    });
51
52    logger.init();
53}
54