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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#[derive(Debug, Clone)]
pub enum LogOutput {
    Log(log::Level),
    LogTarget(log::Level, String),
    StdOut,
    StdErr,
    #[cfg(feature = "log-to-file")]
    File(std::sync::Arc<parking_lot::Mutex<std::fs::File>>),
}

impl From<log::Level> for LogOutput {
    fn from(value: log::Level) -> Self {
        Self::Log(value)
    }
}

impl LogOutput {
    fn print(&self, msg: &str) {
        match self {
            LogOutput::Log(level) => log::log!(level.clone(), "{}", msg),
            LogOutput::LogTarget(level, target) => {
                log::log!(target: target, level.clone(), "{}", msg)
            }
            LogOutput::StdOut => println!("{}", msg),
            LogOutput::StdErr => eprintln!("{}", msg),
            #[cfg(feature = "log-to-file")]
            LogOutput::File(file) => {
                use std::io::Write;

                let mut file = file.lock();
                file.write_all(msg.as_bytes()).ok();
                file.write_all(b"\n").ok();
            }
        }
    }
}

#[derive(Debug)]
pub struct LogItem {
    level: usize,
    title: String,
    value: Option<String>,
}

impl LogItem {
    pub fn new<T: Into<String>, V: Into<String>>(level: usize, title: T, value: Option<V>) -> Self {
        Self {
            level,
            title: title.into(),
            value: value.map(Into::into),
        }
    }
}

impl<T: ToString, V: ToString> From<(usize, T, V)> for LogItem {
    fn from((level, title, value): (usize, T, V)) -> Self {
        Self::new(level, title.to_string(), Some(value.to_string()))
    }
}

impl<T: ToString> From<(usize, T)> for LogItem {
    fn from((level, value): (usize, T)) -> Self {
        Self::new::<_, String>(level, value.to_string(), None)
    }
}

pub struct Logger;

impl Logger {
    pub fn log<T>(output: &LogOutput, loggable: &T)
    where
        T: Loggable,
    {
        Self::log_impl(output, &loggable.into_log())
    }

    fn log_impl(output: &LogOutput, items: &[LogItem]) {
        // TODO: support log items with more than 2 steps of log levels
        items.iter().next().map(|v| output.print(&v.title));

        let right_align = items
            .iter()
            .skip(1)
            .map(|v| v.title.len())
            .max()
            .unwrap_or(0);

        items.iter().skip(1).for_each(|i| {
            let LogItem {
                level,
                title,
                value,
            } = i;

            let front_padding: String = (0..level * 2).map(|_| ' ').collect();

            let (value, value_padding) = if let Some(value) = value {
                let value_padding: String = (0..(right_align - title.len())).map(|_| ' ').collect();
                (value.as_str(), value_padding)
            } else {
                ("", String::new())
            };

            let message = format!("{front_padding}{title}: {value_padding}{value}");
            output.print(&message);
        })
    }
}

pub trait Loggable {
    fn into_log(&self) -> Vec<LogItem>;
}

#[macro_export]
macro_rules ! log_vec {
    [$($msg:tt)*] => {
        crate::to_log!(vec: $($msg)*)
    }
}

#[macro_export]
macro_rules! to_log {
    ([$($array:tt)*],) => {
        vec![$($array)*]
    };

    ([$($array:tt)*], ($level:literal, $title:expr, $value:expr)) => {
        crate::to_log!([$($array)* ($level, $title, $value).into(),],)
    };

    ([$($array:tt)*], ($level:literal, $title:expr)) => {
        crate::to_log!([$($array)* ($level, $title, "").into(),],)
    };

    ([$($array:tt)*], ($level:literal, $title:expr, $value:expr), $($msg:tt)*) => {
        crate::to_log!([$($array)* ($level, $title, $value).into(),], $($msg)*)
    };

    ([$($array:tt)*], ($level:literal, $title:expr), $($msg:tt)*) => {
        crate::to_log!([$($array)* ($level, $title, "").into(),], $($msg)*)
    };

    (vec: $($msg:tt)*) => {
        crate::to_log!([], $($msg)*)
    };
}