use std::fs;
pub struct Logger {
pub name: String,
pub log_history: Vec<String>,
}
impl Logger {
pub fn new(name: &str) -> Logger {
Logger {
name: name.to_owned(),
log_history: Vec::new()
}
}
pub fn info(&mut self, s: &str) {
let log_text = format!("\x1b[0;34m[{}:INFO] {}", self.name, s);
println!("{}", log_text);
self.log_history.push(log_text.to_string());
}
pub fn warn(&mut self, s: &str) {
let log_text = format!("\x1b[0;33m[{}:WARNING] {}", self.name, s);
println!("{}", log_text);
self.log_history.push(log_text);
}
pub fn error(&mut self, s: &str) {
let log_text = format!("\x1b[0;31m[{}:ERROR] {}", self.name, s);
println!("{}", log_text);
self.log_history.push(log_text);
}
pub fn save_to_file(self, path: &str) {
let fixed_log_history: Vec<String> = self.log_history
.iter()
.map(|x| (&x[7..x.len()]).to_string())
.collect();
fs::write(path, fixed_log_history.join("\n")).expect("failed saving logs to file");
}
}