extern crate chrono; extern crate colored;
use chrono::prelude::*;
use std::fs::File;
use std::path::Path;
use std::{env, fs};
#[path = "./terminal.rs"]
mod terminal;
pub struct IOLogger {
pkg: String,
name: String,
file: String,
terminal: terminal::TerminalLogger,
}
impl IOLogger {
fn new(name: &str, file: &str, log_name: Option<&str>) -> IOLogger {
let pkg = log_name.unwrap_or(env!("CARGO_PKG_NAME"));
if !file_exists(file) {
let _file = create_file(file);
}
return IOLogger {
pkg: pkg.to_string(),
name: name.to_string(),
file: file.to_string(),
terminal: terminal::get(name),
};
}
pub fn get_name(&self) -> String {
return format!("{}", self.name);
}
pub fn get_file(&self) -> String {
return format!("{}", self.file);
}
pub fn append_log(&self, content: &str) {
let mut contents: std::string::String = read_file(&self.file, "Something went wrong...");
contents = contents + "\n" + content;
write_file(&self.file, &contents, "Something went wrong...");
}
pub fn info(&self, cont: &str) {
let formatted_str = format!(
"{} [{}:{}] {}: {}",
get_current_time(),
self.pkg,
self.name,
"INFO",
cont.to_string()
);
self.terminal.info(cont);
self.append_log(&formatted_str);
}
pub fn error(&self, cont: &str) {
let formatted_str = format!(
"{} [{}:{}] {}: {}",
get_current_time(),
self.pkg,
self.name,
"ERROR",
cont.to_string()
);
self.terminal.error(cont);
self.append_log(&formatted_str);
}
pub fn fatal(&self, cont: &str) {
let formatted_str = format!(
"{} [{}:{}] {}: {}",
get_current_time(),
self.pkg,
self.name,
"FATAL",
cont.to_string()
);
self.terminal.fatal(cont);
self.append_log(&formatted_str);
}
pub fn critical(&self, cont: &str) {
let formatted_str = format!(
"{} [{}:{}] {}: {}",
get_current_time(),
self.pkg,
self.name,
"CRITICAL",
cont.to_string()
);
self.terminal.critical(cont);
self.append_log(&formatted_str);
}
pub fn debug(&self, cont: &str) {
let formatted_str = format!(
"{} [{}:{}] {}: {}",
get_current_time(),
self.pkg,
self.name,
"DEBUG",
cont.to_string()
);
self.terminal.debug(cont);
self.append_log(&formatted_str);
}
pub fn warn(&self, cont: &str) {
let formatted_str = format!(
"{} [{}:{}] {}: {}",
get_current_time(),
self.pkg,
self.name,
"WARN",
cont.to_string()
);
self.terminal.warn(cont);
self.append_log(&formatted_str);
}
}
pub fn get(name: &str, file: &str) -> IOLogger {
let io_logger = IOLogger::new(name, file, None);
return io_logger;
}
pub fn get_current_time() -> String {
let local_time = Local::now();
return local_time.format("%Y-%m-%d %H:%M:%S").to_string();
}
pub fn read_file(path: &str, expect: &str) -> std::string::String {
return fs::read_to_string(path).expect(expect);
}
pub fn write_file(path: &str, content: &str, expect: &str) -> bool {
fs::write(path, content).expect(expect);
return true;
}
pub fn file_exists(p: &str) -> bool {
let path = Path::new(p);
if path.exists() {
return true;
} else {
return false;
}
}
pub fn create_file(file: &str) -> std::io::Result<()> {
File::create(file)?;
Ok(())
}