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
use log::{log, Level};
use paris::formatter::colorize_string;

use crate::LOG_TARGET;

fn level_to_color(level: Level) -> &'static str {
    match level {
        Level::Info => "blue",
        Level::Warn => "yellow",
        Level::Error => "red",
        _ => "white",
    }
}

/// A BIG log that's very difficult to miss.
pub fn basti_log(level: Level, message: &str) {
    let color = level_to_color(level);
    log!(
        target: LOG_TARGET,
        level,
        "{}",
        colorize_string(format!(
            "<bold><{}>{}\n\n",
            &color,
            "-".repeat(message.len())
        ))
    );
    log!(
        target: LOG_TARGET,
        level,
        "{}",
        colorize_string(format!("<bold><{}>{}\n\n", &color, message))
    );
    log!(
        target: LOG_TARGET,
        level,
        "{}",
        colorize_string(format!(
            "<bold><{}>{}\n\n",
            &color,
            "-".repeat(message.len())
        ))
    );
}

/// Temporarily demote the log level to a specific level and restore on drop.
pub struct LogLevelGuard(log::LevelFilter);
impl LogLevelGuard {
    pub fn new(new_level: log::LevelFilter) -> Self {
        let old_level = log::max_level();
        log::set_max_level(new_level);
        Self(old_level)
    }

    /// Only show errors.
    pub fn only_errors() -> Self {
        Self::new(log::LevelFilter::Error)
    }
}

impl Drop for LogLevelGuard {
    fn drop(&mut self) {
        log::set_max_level(self.0);
    }
}