geph5_client/
logging.rs

1use arc_writer::ArcWriter;
2use once_cell::sync::Lazy;
3use std::sync::{Arc, Mutex};
4use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
5
6/// In-memory buffer for JSON formatted logs
7static JSON_LOGS: Lazy<ArcWriter<Vec<u8>>> = Lazy::new(|| ArcWriter::new(Vec::new()));
8
9/// Initialize the tracing subscribers for logging
10pub fn init_logging() -> anyhow::Result<()> {
11    // Create a JSON writer that writes to our in-memory buffer
12    let json_writer = JSON_LOGS.clone();
13
14    tracing_subscriber::registry()
15        // Standard logs to stderr (for console display)
16        .with(fmt::layer().compact().with_writer(std::io::stderr))
17        // Text logs to the LOGS global buffer
18        .with(fmt::layer().json().with_writer(move || json_writer.clone()))
19        // Set filtering based on environment or defaults
20        .with(
21            EnvFilter::builder()
22                .with_default_directive("geph=debug".parse()?)
23                .from_env_lossy(),
24        )
25        .init();
26
27    Ok(())
28}
29
30/// Get the current JSON logs as a String
31pub fn get_json_logs() -> String {
32    let logs = JSON_LOGS.lock();
33
34    // Convert the byte buffer to a string
35    let log_string = String::from_utf8_lossy(&logs);
36
37    log_string.to_string()
38}