monorail/app/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
pub(crate) mod analyze;
pub(crate) mod checkpoint;
pub(crate) mod log;
pub(crate) mod out;
pub(crate) mod result;
pub(crate) mod run;
pub(crate) mod target;

use std::result::Result;

use tracing_subscriber::filter::{EnvFilter, LevelFilter};
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::{fmt, Registry};

use crate::core::error::MonorailError;

// Custom formatter to match chrono's strict RFC3339 compliance.
struct UtcTimestampWithOffset;

impl fmt::time::FormatTime for UtcTimestampWithOffset {
    fn format_time(&self, w: &mut fmt::format::Writer<'_>) -> std::fmt::Result {
        let now = chrono::Utc::now();
        // Format the timestamp as "YYYY-MM-DDTHH:MM:SS.f+00:00"
        write!(w, "{}", now.format("%Y-%m-%dT%H:%M:%S%.f+00:00"))
    }
}

pub(crate) fn setup_tracing(format: &str, level: u8) -> Result<(), MonorailError> {
    let env_filter = EnvFilter::default();
    let level_filter = match level {
        0 => LevelFilter::OFF,
        1 => LevelFilter::INFO,
        2 => LevelFilter::DEBUG,
        _ => LevelFilter::TRACE,
    };

    let registry = Registry::default().with(env_filter.add_directive(level_filter.into()));
    match format {
        "json" => {
            let json_fmt_layer = tracing_subscriber::fmt::layer()
                .json()
                .with_current_span(false)
                .with_span_list(false)
                .with_target(false)
                .flatten_event(true)
                .with_timer(UtcTimestampWithOffset);
            tracing::subscriber::set_global_default(registry.with(json_fmt_layer))
                .map_err(|e| MonorailError::from(e.to_string()))?;
        }
        _ => {
            let plain_fmt_layer = tracing_subscriber::fmt::layer()
                .with_target(true)
                .with_thread_names(true)
                .with_timer(UtcTimestampWithOffset);
            tracing::subscriber::set_global_default(registry.with(plain_fmt_layer))
                .map_err(|e| MonorailError::from(e.to_string()))?;
        }
    }
    Ok(())
}