antares_get_data/src/tools/logger.rs

44 lines
1.0 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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));
}
}