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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
//! Rotating logging API
//! This can be used to create a configurable log
//! that saves to a file and optionally
//! prints to stdout as well.

use std::{
    fs, env,
    process, thread,
    path::PathBuf,
    fmt::{Display, Formatter, Result as FmtResult},
    sync::{RwLock, Mutex, Arc},
    panic::{self, PanicInfo}
};
use backtrace::Backtrace;
use chrono::{Timelike, Datelike, Local};
use colored::{Colorize, ColoredString};
use lazy_static::lazy_static;

lazy_static! {
    static ref PANIC_LOG: RwLock<Option<Log>> = RwLock::new(None);
}

/// An automatic rotating log based on the current date
/// 
/// It logs output like the following
/// 
/// `[hh:mm:ss] [LEVEL]: message`
#[derive(Clone)]
pub struct Log {
    name: String,
    folder: String,
    path: PathBuf,
    main_log_path: Option<PathBuf>,
    runlock: Arc<Mutex<()>>
}

impl Log {
    /// Creates a new log handle
    ///
    /// Logs will be stored under `$HOME/.local/share/<folder>` and
    /// named `<log_name>-<year>-<month>-<day>.log`
    ///
    /// Panics: You don't seem to have a home folder. Make sure $HOME is set.
    pub fn new(log_name: &str, folder: &str) -> Log {
        let path = PathBuf::from(format!("{}/.local/share/{folder}", env::var("HOME").expect("Where the hell is your home folder?!")));
        fs::create_dir_all(&path).unwrap_or(());

        Log {
            name: log_name.to_string(),
            folder: folder.to_string(),
            path,
            main_log_path: None,
            runlock: Arc::default()
        }
    }

    /// If this is true, there will be a main application log under
    /// `/tmp/<folder name>-<username>/app.log`
    ///
    /// This log will be available for viewing until the system is rebooted
    pub fn main_log(mut self, main_log: bool) -> Log {
        if main_log {
            let user = env::var("USER").unwrap();
            let main_log_path = PathBuf::from(format!("/tmp/{}-{user}", self.folder));
            fs::create_dir_all(&main_log_path).unwrap_or(());
            self.main_log_path = Some(main_log_path);
        }

        self
    }

    /// Print a line to the log
    /// 
    /// This will print any object that implements `Display`
    pub fn line<T: Display>(&self, level: LogLevel, text: T, print_stdout: bool) {
        let run = self.runlock.lock().unwrap();
        if let LogLevel::Debug(false) = level {
            return;
        }

        let log_path = self.log_path();
        let mut log = fs::read_to_string(&log_path).unwrap_or_default();
        let text_str = text.to_string();

        for line in text_str.lines() {
            let now = Local::now();
            let msg = format!("[{}:{:02}:{:02}] [{level}]: {line}\n", now.hour(), now.minute(), now.second());
            if print_stdout { print!("{}", level.colorize(&msg)); }
            log.push_str(&msg);
        }

        fs::write(log_path, &log).expect("Unable to write to log file!");

        if let Some(main_log_path) = self.main_log_path() {
            let mut main_log = fs::read_to_string(&main_log_path).unwrap_or_default();
            for line in text_str.lines() {
                let now = Local::now();
                let msg = format!("[{}:{:02}:{:02}] [{level}]: {line}\n", now.hour(), now.minute(), now.second());
                main_log.push_str(&msg);
            }

            fs::write(main_log_path, main_log).expect("Unable to write to log file!");
        }

        drop(run);
    }
    
    /// Print a line to the log (basic info)
    pub fn line_basic<T: Display>(&self, text: T, print_stdout: bool) { self.line(LogLevel::Info, text, print_stdout); }

    /// Should this log handle be used to report application panics? This 
    /// creates a panic handler that logs the thread panicked, where the panic occurred in the source
    /// and the backtrace.
    /// 
    /// This could be useful in conjunction with libraries that block stdout/stderr like cursive
    pub fn report_panics(&self, report: bool) {
        if report {
            *(PANIC_LOG.write().unwrap()) = Some(self.clone());
            panic::set_hook(Box::new(panic_handler));
        }
        else {
            *(PANIC_LOG.write().unwrap()) = None;
            drop(panic::take_hook());
        }
    }

    /// Returns the path of the main log for viewing
    ///
    /// Returns `None` if the main log is not enabled
    pub fn main_log_path(&self) -> Option<PathBuf> {
        self.main_log_path.as_ref()
            .map(|path| path.join("app.log"))
    }

    /// Returns the path of the log file that is currently being written to
    pub fn log_path(&self) -> PathBuf {
        let now = Local::now();
        let path = format!("{}-{}-{}-{}.log", self.name, now.year(), now.month(), now.day());
        self.path.join(path)
    }
}

/// Severity level for a log entry
#[derive(Copy, Clone)]
pub enum LogLevel {
    /// Possibly useful information
    Info,

    /// Debug information, can optionally be hidden
    Debug(bool),

    /// This might cause trouble
    Warn,

    /// Oops...
    /// 
    /// Indicates an error has occurred
    Error,

    /// The Application has panicked
    Fatal
}

impl LogLevel {
    fn colorize(&self, input: &str) -> ColoredString {
        match self {
            Self::Debug(_) => input.cyan(),
            Self::Info => input.green(),
            Self::Warn => input.bright_yellow(),
            Self::Error => input.bright_red(),
            Self::Fatal => input.bright_red().on_black()
        }
    }
}

impl Display for LogLevel {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        match *self {
            LogLevel::Info => write!(f, "INFO"),
            LogLevel::Debug(_) => write!(f, "DEBUG"),
            LogLevel::Warn => write!(f, "WARN"),
            LogLevel::Error => write!(f, "ERROR"),
            LogLevel::Fatal => write!(f, "FATAL")
        }
    }
}

fn panic_handler(info: &PanicInfo) {
    let backtrace = format!("{:?}", Backtrace::new());
    let maybe_log = PANIC_LOG.read().unwrap();
    let panic_log = if let Some(ref log) = &*maybe_log {
        log
    }
    else {
        eprintln!("Internal Error");
        process::exit(101);
    };

    let cur_thread = thread::current();
    let thread_disp = if let Some(name) = cur_thread.name() {
        name.to_string()
    }
    else {
        format!("{:?}", cur_thread.id())
    };

    if let Some(loc) = info.location() {
        panic_log.line(LogLevel::Fatal, format!("Thread '{thread_disp}' panicked at {loc}"), true);
    }
    else {
        panic_log.line(LogLevel::Fatal, format!("Thread '{thread_disp}' panicked"), true);
    }

    if let Some(payload) = info.payload().downcast_ref::<String>() {
        panic_log.line(LogLevel::Fatal, format!("Error: {payload}"), true);
    }

    panic_log.line(LogLevel::Fatal, format!("Backtrace:\n{backtrace}"), true);
}