LD-Uninstaller/src-tauri/src/services/logger.rs

66 lines
1.8 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 chrono::Local;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::sync::Mutex;
static LOGGER: Mutex<Option<AppLogger>> = Mutex::new(None);
pub struct AppLogger {
pub log_file: PathBuf,
}
impl AppLogger {
pub fn init(config_dir: &std::path::Path) {
let logs_dir = config_dir.join("Logs");
let _ = fs::create_dir_all(&logs_dir);
let log_file = logs_dir.join("app.log");
let logger = AppLogger { log_file };
let mut guard = match LOGGER.lock() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
};
*guard = Some(logger);
}
pub fn log(level: &str, message: &str) {
let guard = match LOGGER.lock() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
};
if let Some(logger) = guard.as_ref() {
// Log rotation: 5 MB aşılırsa app.log.old olarak döndür
if let Ok(meta) = fs::metadata(&logger.log_file) {
if meta.len() > 5 * 1024 * 1024 {
let old_file = logger.log_file.with_extension("log.old");
let _ = fs::rename(&logger.log_file, old_file);
}
}
let timestamp = Local::now().format("%Y-%m-%d %H:%M:%S%.3f");
let line = format!("[{}] [{}] {}\n", timestamp, level, message);
if let Ok(mut file) = OpenOptions::new()
.create(true)
.append(true)
.open(&logger.log_file)
{
let _ = file.write_all(line.as_bytes());
}
}
}
}
pub fn log_info(msg: &str) {
AppLogger::log("INFO", msg);
}
pub fn log_warn(msg: &str) {
AppLogger::log("WARN", msg);
}
pub fn log_error(msg: &str) {
AppLogger::log("ERROR", msg);
}