add rotating file logs

This commit is contained in:
Hay1tsme 2023-11-16 23:45:20 -05:00
parent addf075c8f
commit 8e534cd9e7
1 changed files with 27 additions and 2 deletions

View File

@ -1,6 +1,6 @@
use once_cell::sync::OnceCell;
use std::sync::atomic::*;
use std::fs::{OpenOptions, File, create_dir_all};
use std::fs::{OpenOptions, File, create_dir_all, copy};
use std::io::Write;
#[derive(Debug, PartialEq, PartialOrd)]
@ -50,6 +50,8 @@ static LEVEL: OnceCell<LogLevel> = OnceCell::new();
static LOG_FILE: OnceCell<File> = OnceCell::new();
static HAS_INITED: AtomicBool = AtomicBool::new(false);
static FILE_IS_GOOD: AtomicBool = AtomicBool::new(false);
static FILE_DATE: OnceCell<String> = OnceCell::new();
static FILE_FOLDER: OnceCell<String> = OnceCell::new();
pub fn init_logger(log_folder: &str, level: LogLevel) {
if HAS_INITED.load(Ordering::Relaxed) {
@ -59,7 +61,10 @@ pub fn init_logger(log_folder: &str, level: LogLevel) {
HAS_INITED.store(true, Ordering::Relaxed);
let log_file = format!("{}/apollo.log", log_folder);
let _ = FILE_DATE.set(chrono::offset::Local::now().format("%F").to_string());
let log_file = format!("{}/whisper.log", log_folder);
let _ = FILE_FOLDER.set(log_folder.to_string());
let dir_create_result: Result<(), std::io::Error> = create_dir_all(log_folder);
if dir_create_result.is_err() {
@ -93,6 +98,26 @@ pub fn log(level: LogLevel, module: &str, submodule: &str, message: &str) {
timestamp, level, module, submodule, message
);
let new_time = chrono::offset::Local::now().format("%F").to_string();
if !FILE_DATE.get().unwrap().eq(&new_time) {
let _ = FILE_DATE.set(new_time.clone());
let log_folder = FILE_FOLDER.get().unwrap();
let log_file = format!("{}/apollo.log", log_folder);
match copy(log_file.clone(), format!("{}/apollo-{}.log", log_folder, new_time)) {
Err(e) => println!("Failed to copy over log! {:?}", e),
_ => {
match File::create(log_file) {
Err(e) => println!("Failed to open log file! {}", e),
Ok(f) => {
let _ = LOG_FILE.set(f);
}
}
}
}
}
if level >= *LEVEL.get().unwrap() {
println!("{logstr}");