mirror of
https://github.com/bleackstorm/SteamFrame-FPV-Control-Center.git
synced 2026-12-03 07:31:57 +01:00
205 lines
6.3 KiB
Rust
205 lines
6.3 KiB
Rust
use chrono::Local;
|
|
use log::{Level, LevelFilter, Log, Metadata, Record};
|
|
use parking_lot::Mutex;
|
|
use std::collections::VecDeque;
|
|
use std::fs::OpenOptions;
|
|
use std::io::{BufWriter, Write};
|
|
use std::sync::atomic::{AtomicU64, Ordering};
|
|
use std::sync::mpsc::{self, SyncSender};
|
|
use std::sync::Arc;
|
|
use std::thread;
|
|
|
|
const MAX_LOG_ENTRIES: usize = 1000;
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum LogFilter {
|
|
All,
|
|
WarningsAndErrors,
|
|
ErrorsOnly,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct LogEntry {
|
|
pub timestamp: String,
|
|
pub level: Level,
|
|
pub target: String,
|
|
pub message: String,
|
|
}
|
|
|
|
pub struct LogBuffer {
|
|
pub entries: VecDeque<LogEntry>,
|
|
pub error_count: usize,
|
|
pub warn_count: usize,
|
|
pub revision: Arc<AtomicU64>,
|
|
}
|
|
|
|
impl Default for LogBuffer {
|
|
fn default() -> Self {
|
|
Self {
|
|
entries: VecDeque::new(),
|
|
error_count: 0,
|
|
warn_count: 0,
|
|
revision: Arc::new(AtomicU64::new(0)),
|
|
}
|
|
}
|
|
}
|
|
|
|
enum FileLogCmd {
|
|
Line { text: String, flush: bool },
|
|
Flush,
|
|
FlushSync(mpsc::SyncSender<()>),
|
|
}
|
|
|
|
static GLOBAL_LOG_TX: std::sync::OnceLock<SyncSender<FileLogCmd>> = std::sync::OnceLock::new();
|
|
|
|
/// Logger centralisé capturant tous les événements et erreurs pour l'interface graphique
|
|
/// et les enregistrant sur un thread I/O dédié (stderr + fichier) sans jamais bloquer les boucles temps réel.
|
|
pub struct GuiLogger {
|
|
buffer: Arc<Mutex<LogBuffer>>,
|
|
file_tx: Option<SyncSender<FileLogCmd>>,
|
|
}
|
|
|
|
impl GuiLogger {
|
|
pub fn init(log_file_path: &str) -> Arc<Mutex<LogBuffer>> {
|
|
let buffer = Arc::new(Mutex::new(LogBuffer::default()));
|
|
|
|
let file_opt = OpenOptions::new()
|
|
.create(true)
|
|
.append(true)
|
|
.open(log_file_path)
|
|
.ok();
|
|
|
|
let (tx, rx) = mpsc::sync_channel::<FileLogCmd>(512);
|
|
let file_tx = thread::Builder::new()
|
|
.name("fpv-log-writer".into())
|
|
.spawn(move || {
|
|
let mut writer = file_opt.map(BufWriter::new);
|
|
let mut stderr = std::io::stderr();
|
|
while let Ok(cmd) = rx.recv() {
|
|
match cmd {
|
|
FileLogCmd::Line { text, flush } => {
|
|
let _ = stderr.write_all(text.as_bytes());
|
|
if let Some(ref mut w) = writer {
|
|
let _ = w.write_all(text.as_bytes());
|
|
if flush {
|
|
let _ = w.flush();
|
|
}
|
|
}
|
|
}
|
|
FileLogCmd::Flush => {
|
|
let _ = stderr.flush();
|
|
if let Some(ref mut w) = writer {
|
|
let _ = w.flush();
|
|
}
|
|
}
|
|
FileLogCmd::FlushSync(ack) => {
|
|
let _ = stderr.flush();
|
|
if let Some(ref mut w) = writer {
|
|
let _ = w.flush();
|
|
}
|
|
let _ = ack.send(());
|
|
}
|
|
}
|
|
}
|
|
let _ = stderr.flush();
|
|
if let Some(ref mut w) = writer {
|
|
let _ = w.flush();
|
|
}
|
|
})
|
|
.ok()
|
|
.map(|_| {
|
|
let _ = GLOBAL_LOG_TX.set(tx.clone());
|
|
tx
|
|
});
|
|
|
|
let logger = Box::new(Self {
|
|
buffer: Arc::clone(&buffer),
|
|
file_tx,
|
|
});
|
|
|
|
if log::set_boxed_logger(logger).is_ok() {
|
|
log::set_max_level(LevelFilter::Info);
|
|
}
|
|
|
|
buffer
|
|
}
|
|
|
|
/// Attend la vidange complète du fichier journal et de `stderr` avant la fin du processus.
|
|
pub fn flush_blocking() {
|
|
if let Some(tx) = GLOBAL_LOG_TX.get() {
|
|
let (ack_tx, ack_rx) = mpsc::sync_channel::<()>(1);
|
|
if tx.send(FileLogCmd::FlushSync(ack_tx)).is_ok() {
|
|
let _ = ack_rx.recv_timeout(std::time::Duration::from_millis(500));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Log for GuiLogger {
|
|
fn enabled(&self, metadata: &Metadata) -> bool {
|
|
let t = metadata.target();
|
|
if t.starts_with("blade_graphics")
|
|
|| t.starts_with("naga")
|
|
|| t.starts_with("zbus")
|
|
|| t.starts_with("tracing")
|
|
|| t.starts_with("calloop")
|
|
|| t.starts_with("winit")
|
|
{
|
|
return metadata.level() <= Level::Warn;
|
|
}
|
|
metadata.level() <= Level::Info
|
|
}
|
|
|
|
fn log(&self, record: &Record) {
|
|
if !self.enabled(record.metadata()) {
|
|
return;
|
|
}
|
|
|
|
let now = Local::now().format("%H:%M:%S%.3f").to_string();
|
|
let entry = LogEntry {
|
|
timestamp: now,
|
|
level: record.level(),
|
|
target: record.target().to_string(),
|
|
message: format!("{}", record.args()),
|
|
};
|
|
|
|
// Envoi non-bloquant vers le thread I/O dédié (stderr + fichier, jamais de syscall bloquant ici)
|
|
if let Some(ref tx) = self.file_tx {
|
|
let line = format!(
|
|
"[{}] [{:<5}] ({}) {}\n",
|
|
entry.timestamp, entry.level, entry.target, entry.message
|
|
);
|
|
let _ = tx.try_send(FileLogCmd::Line {
|
|
text: line,
|
|
flush: record.level() <= Level::Warn,
|
|
});
|
|
}
|
|
|
|
// Ajout dans le tampon de l'interface graphique
|
|
let mut lock = self.buffer.lock();
|
|
if record.level() == Level::Error {
|
|
lock.error_count += 1;
|
|
} else if record.level() == Level::Warn {
|
|
lock.warn_count += 1;
|
|
}
|
|
|
|
if lock.entries.len() >= MAX_LOG_ENTRIES {
|
|
if let Some(old) = lock.entries.pop_front() {
|
|
match old.level {
|
|
Level::Error => lock.error_count = lock.error_count.saturating_sub(1),
|
|
Level::Warn => lock.warn_count = lock.warn_count.saturating_sub(1),
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
lock.entries.push_back(entry);
|
|
lock.revision.fetch_add(1, Ordering::Release);
|
|
}
|
|
|
|
fn flush(&self) {
|
|
if let Some(ref tx) = self.file_tx {
|
|
let _ = tx.try_send(FileLogCmd::Flush);
|
|
}
|
|
}
|
|
}
|