pub mod logger {
use chrono::Local;
use std::process;
use std::fs;
pub struct Logger {
pub log: Vec<String>,
filepath: String,
}
impl Logger {
pub fn new(filepath: String) -> Logger {
return Logger {
log: vec![],
filepath
}
}
pub fn info(&mut self, text: String) {
let info = format!("[INFO] {} >> {}", Local::now().format("%H:%M:%S").to_string(), text);
println!("{}", info.clone());
self.log.push(info);
}
pub fn error(&mut self, text: String) {
let error = format!("[ERROR] {} >> {}", Local::now().format("%H:%M:%S").to_string(), text);
println!("{}", error.clone());
self.log.push(error);
}
pub fn warning(&mut self, text: String) {
let warning = format!("[WARNING] {} >> {}", Local::now().format("%H:%M:%S").to_string(), text);
println!("{}", warning.clone());
self.log.push(warning);
}
pub fn critical(&mut self, text: String) {
let error = format!("[CRITICAL ERROR] {} >> {}", Local::now().format("%H:%M:%S").to_string(), text);
println!("{}", error.clone());
self.log.push(error);
self.export();
process::exit(-1);
}
pub fn custom(&mut self, _type: String, text: String) {
let custom = format!("[{}] {} >> {}", _type, Local::now().format("%H:%M:%S").to_string(), text);
println!("{}", custom.clone());
self.log.push(custom);
}
pub fn export(&mut self) {
let text = format!("# Log generated by Logcat v0.0.1\n# Exported at {}\n\n{}", Local::now().format("%H:%M:%S").to_string(), self.log.join("\n"));
let file = fs::write(self.filepath.clone(), text);
match file {
Ok(..) => {
let _ = &self.info(format!("Log exported successfully!").to_string());
},
Err(error) => {
let _ = &self.error(format!("Failed to export log! {}", error).to_string());
}
}
}
}
}
#[cfg(test)]
mod tests {
use crate::logger::Logger;
#[test]
fn it_works() {
let mut logger = Logger::new(String::from("filename.txt"));
logger.info(String::from("This is info!"));
logger.warning(String::from("This is warning!"));
logger.error(String::from("This is error!"));
logger.custom(String::from("CUSTOM"), String::from("This is custom log!"));
logger.export(); logger.critical(String::from("This is critical error! Program will exit with code -1!"));
}
}