44 lines
1.0 KiB
Rust
44 lines
1.0 KiB
Rust
use std::fs;
|
||
use std::io::Write;
|
||
use std::path::PathBuf;
|
||
use chrono::Local;
|
||
|
||
pub struct Logger {
|
||
log_file: PathBuf,
|
||
}
|
||
|
||
impl Logger {
|
||
pub fn init() -> std::io::Result<Self> {
|
||
let log_dir = PathBuf::from("log");
|
||
fs::create_dir_all(&log_dir)?;
|
||
|
||
let today = Local::now().format("%Y-%m-%d").to_string();
|
||
let log_file = log_dir.join(format!("{}.log", today));
|
||
|
||
Ok(Logger { log_file })
|
||
}
|
||
|
||
pub fn log(&self, message: &str) {
|
||
let timestamp = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
|
||
let formatted = format!("[{}] {}", timestamp, message);
|
||
|
||
println!("{}", formatted);
|
||
|
||
if let Ok(mut file) = fs::OpenOptions::new()
|
||
.create(true)
|
||
.append(true)
|
||
.open(&self.log_file)
|
||
{
|
||
let _ = writeln!(file, "{}", formatted);
|
||
}
|
||
}
|
||
|
||
pub fn log_info(&self, message: &str) {
|
||
self.log(&format!("ℹ {}", message));
|
||
}
|
||
|
||
pub fn log_error(&self, error: &str) {
|
||
self.log(&format!("✗ Error: {}", error));
|
||
}
|
||
}
|