Feat: Fügt logging in eine tmp-Datei hinzu.

This commit is contained in:
2025-08-18 12:48:37 +02:00
parent 1eb72f9943
commit 31dc99b21d
2 changed files with 56 additions and 2 deletions

View File

@@ -1,7 +1,12 @@
use std::any::Any;
use std::fmt::{Display, Formatter};
use std::io::{IsTerminal, stdout};
use std::sync::OnceLock;
use std::io::{IsTerminal, stdout, Write};
use std::sync::{OnceLock, Mutex};
use std::fs::{create_dir_all, OpenOptions, File};
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{env, process};
use time::{OffsetDateTime, macros::format_description};
#[derive(PartialEq)]
@@ -26,6 +31,8 @@ impl Display for LogLevel {
static IS_TERMINAL: OnceLock<bool> = OnceLock::new();
static LOG_LEVEL: LogLevel = LogLevel::Debug; // TODO: LogLevel aus Config laden
static LOG_FILE: OnceLock<Mutex<Option<File>>> = OnceLock::new();
pub fn log(tag: &str, message: &str, log_level: LogLevel) {
if log_level.type_id() >= LOG_LEVEL.type_id() {
let message: String = format_message(tag, message, &log_level);
@@ -37,6 +44,14 @@ pub fn log(tag: &str, message: &str, log_level: LogLevel) {
println!("{}", message)
}
}
let file_lock = get_or_init_log_file();
if let Ok(mut guard) = file_lock.lock() {
if let Some(f) = guard.as_mut() {
let _ = writeln!(f, "{}", message);
let _ = f.flush();
}
}
}
}
@@ -71,3 +86,40 @@ fn format_message(tag: &str, message: &str, log_level: &LogLevel) -> String {
&LogLevel::Debug => format!("{}{}", "🚧", message),
}
}
fn get_or_init_log_file() -> &'static Mutex<Option<File>> {
LOG_FILE.get_or_init(|| {
let file = open_log_file().ok();
Mutex::new(file)
})
}
fn open_log_file() -> std::io::Result<File> {
let program = program_name();
let rand = "13692bbf-a93b-43e9-9cc6-f05f94a8cfb6";
let base_dir = format!("/tmp/{}-{}", program, rand);
let today_fmt = format_description!("[year]-[month]-[day]");
let date_str = OffsetDateTime::now_local()
.unwrap_or(OffsetDateTime::now_utc())
.format(today_fmt)
.unwrap_or_else(|_| "0000-00-00".to_string());
let file_name = format!("log-{}.log", date_str);
let mut dir = PathBuf::from(base_dir);
create_dir_all(&dir)?;
dir.push(file_name);
OpenOptions::new()
.create(true)
.append(true)
.open(dir)
}
fn program_name() -> String {
env::current_exe()
.ok()
.and_then(|p| p.file_stem().map(|s| s.to_string_lossy().to_string()))
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "app".to_string())
}

View File

@@ -3,6 +3,8 @@ use crate::log::LogLevel;
mod log;
fn main() {
log::log("main", "========== PROGRAMM START ==========", LogLevel::Info);
log::log("main", "Hello, world!", LogLevel::Error);
log::log("main", "Hello, world!", LogLevel::Warn);
log::log("main", "Hello, world!", LogLevel::Info);