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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use fern::colors::{Color, ColoredLevelConfig};
use log::LevelFilter;

/// Initializes logging to file and standard output.
/// All logs with level `debug`(with parameter `verbose`=true or system variable `RUST_LOG`="debug") or above
/// will be recorded in `./logs/<date>.log`.
/// Logs with level `info` and above will be output to standard output, with colored tag.
///
/// # Example
///
/// ```
/// use lib_flutter_rust_bridge_codegen::init_logger;
/// init_logger("./logs/", false).expect("failed to initialize log");
/// ```
pub fn init_logger(path: &str, verbose: bool) -> Result<(), fern::InitError> {
    let colored_output = ColoredLevelConfig::new()
        .error(Color::Red)
        .warn(Color::Yellow)
        .info(Color::Green)
        .debug(Color::Blue)
        .trace(Color::BrightBlack);

    let mut d = fern::Dispatch::new();
    d = d.format(move |out, message, record| {
        let format = if atty::is(atty::Stream::Stdout) {
            format!(
                "{} [{}] {}",
                chrono::Local::now().format("%Y/%m/%d %H:%M:%S"),
                colored_output.color(record.level()),
                message
            )
        } else {
            format!(
                "{} [{}] {}",
                chrono::Local::now().format("%Y/%m/%d %H:%M:%S"),
                record.level(),
                message
            )
        };
        out.finish(format_args!("{}", format))
    });

    std::fs::create_dir_all(path).unwrap();
    match std::env::var("RUST_LOG")
        .unwrap_or_else(|_| if verbose { "debug" } else { "info" }.to_owned())
        .as_str()
    {
        // #[cfg(debug_assertions)]
        "debug" => d
            .level(LevelFilter::Debug)
            .chain(fern::DateBased::new(path, "%Y-%m-%d.log"))
            .chain(std::io::stdout())
            .apply()?,
        // #[cfg(not(debug_assertions))]
        "info" => d
            .level(LevelFilter::Info)
            .level_for("cbindgen", LevelFilter::Error)
            .chain(std::io::stdout())
            .apply()?,
        _ => panic!("only allow \"debug\" and \"info\""),
    }

    let prev = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        log::error!("{}", info);
        prev(info);
    }));

    Ok(())
}