use std::fs;
use std::fs::OpenOptions;
use std::io::{BufWriter, Result, Write};
use chrono::Utc;
pub fn log<S: AsRef<str>>(to_log: S) {
println!("{}", mk_str(to_log.as_ref()));
}
pub fn log_to_file<S: AsRef<str>, T: AsRef<str>>(to_log: S, file_name: T) -> Result<()> {
let file_name = file_name.as_ref();
if let Err(_) = OpenOptions::new()
.create(true)
.open(file_name) {
mkdirs(file_name)?;
}
let file;
if let Ok(f) = OpenOptions::new()
.create(true)
.write(true)
.append(true)
.open(file_name) { file = f; } else {
mkdirs(file_name)?;
file = OpenOptions::new()
.create(true)
.write(true)
.append(true)
.open(file_name)?;
}
let mut writer = BufWriter::new(file);
let msg = mk_str(to_log.as_ref());
writeln!(writer, "{msg}")?;
Ok(())
}
fn mkdirs(path: &str) -> Result<()> {
let slash = get_slash();
let vec = path.rsplitn(2, slash).collect::<Vec<_>>();
if let Some(path) = vec.get(1) {
return fs::create_dir_all(path);
}
Ok(())
}
#[cfg(target_os = "linux")]
fn get_slash() -> &'static str {
"/"
}
#[cfg(target_os = "windows")]
fn get_slash() -> &'static str {
"\\"
}
pub fn log_to_dyn_file<S: AsRef<str>, T: AsRef<str>, U: AsRef<str>>
(to_log: S, file_path: Option<T>, file_name: U) -> Result<()> {
let date = Utc::now()
.format("%Y-%m-%d")
.to_string();
let file_name = file_name.as_ref();
let path;
if let Some(p) = file_path {
let p = p.as_ref();
let slash = get_slash();
if !p.ends_with(slash) {
path = format!("{p}{slash}");
} else { path = String::from(p) }
} else { path = String::new() }
let combined_file_path = format!("{path}{date}-{file_name}");
log_to_file(to_log, &combined_file_path)?;
Ok(())
}
fn mk_str(to_log: &str) -> String {
let now = Utc::now()
.format("[%Y-%m-%d] - [%H:%M:%S]")
.to_string();
let msg = format!("{now} - {to_log}");
msg
}