Skip to main content

claviron_logging/
lib.rs

1use std::{env, io};
2
3#[cfg(feature = "pipeline")]
4pub mod pipeline;
5mod system;
6
7pub use system::{SystemLog, SystemLogConfig, SystemLogFormat};
8
9/// Listen for [`ReopenLogs`](claviron_runtime::ReopenLogs) and reopen this
10/// process's system log file. Registered once, before runnables start.
11pub fn register(
12    state: &claviron_runtime::AppState
13) -> claviron_runtime::registry::Result<()> {
14    state.events().listen::<claviron_runtime::ReopenLogs, _>(|_, _| async {
15        system::reopen();
16        Ok(())
17    })
18}
19
20use claviron_runtime::RunMode;
21use tracing_subscriber::EnvFilter;
22use tracing_subscriber::fmt::format::Writer;
23use tracing_subscriber::fmt::time::LocalTime;
24use tracing_subscriber::fmt::{self, FormatEvent, FormatFields};
25use tracing_subscriber::layer::SubscriberExt;
26use tracing_subscriber::registry::LookupSpan;
27use tracing_subscriber::util::SubscriberInitExt;
28
29type Timer = LocalTime<time::format_description::well_known::Rfc3339>;
30
31/// Custom Formatter to prepend role
32/// Handles: Time, Level, Target, Role -> delegates Message to inner
33struct RoleEventFormat<F> {
34    run_mode: RunMode,
35    inner: F,
36    timer: Option<Timer>,
37    ansi: bool,
38}
39
40impl<S, N, F> FormatEvent<S, N> for RoleEventFormat<F>
41where
42    S: tracing::Subscriber + for<'a> LookupSpan<'a>,
43    N: for<'a> FormatFields<'a> + 'static,
44    F: FormatEvent<S, N>,
45{
46    fn format_event(
47        &self,
48        ctx: &fmt::FmtContext<'_, S, N>,
49        mut writer: Writer<'_>,
50        event: &tracing::Event<'_>,
51    ) -> std::fmt::Result {
52        // 1-3. Time/Level/Target, for a line read on its own (console, system
53        // log file). Journald records time, unit and pid itself, and gets
54        // neither. `ansi` only colours what is written.
55        if let Some(timer) = &self.timer {
56            use tracing_subscriber::fmt::time::FormatTime;
57            let level = *event.metadata().level();
58            let target = event.metadata().target();
59            if self.ansi {
60                write!(writer, "\x1b[2m")?; // Dim
61                timer.format_time(&mut writer)?;
62                write!(writer, "\x1b[0m ")?;
63                let color_code = match level {
64                    tracing::Level::TRACE => "\x1b[35m", // Purple
65                    tracing::Level::DEBUG => "\x1b[34m", // Blue
66                    tracing::Level::INFO => "\x1b[32m",  // Green
67                    tracing::Level::WARN => "\x1b[33m",  // Yellow
68                    tracing::Level::ERROR => "\x1b[31m", // Red
69                };
70                write!(writer, "{}{:<5}\x1b[0m ", color_code, level.as_str())?;
71                write!(writer, "\x1b[2m{}:\x1b[0m ", target)?;
72            } else {
73                timer.format_time(&mut writer)?;
74                write!(writer, " {:<5} {}: ", level.as_str(), target)?;
75            }
76        }
77
78        // 4. Role
79        match self.run_mode {
80            RunMode::Worker(worker_id) => {
81                if self.ansi {
82                    write!(
83                        writer,
84                        "\x1b[2m[Worker #{}]\x1b[0m ",
85                        worker_id.raw()
86                    )?;
87                } else {
88                    write!(writer, "[Worker #{}] ", worker_id.raw())?;
89                }
90            }
91            RunMode::Master => {
92                if self.ansi {
93                    write!(writer, "\x1b[2m[Master]\x1b[0m ")?;
94                } else {
95                    write!(writer, "[Master] ")?;
96                }
97            }
98            RunMode::Standalone => {}
99        }
100
101        // 5. Message (inner format handles the rest)
102        self.inner.format_event(ctx, writer, event)
103    }
104}
105
106/// The system log file's layer: the console's line, without colour.
107fn system_log_layer<S>(
108    run_mode: RunMode,
109    system_log: Option<SystemLog>,
110) -> Option<impl tracing_subscriber::Layer<S>>
111where
112    S: tracing::Subscriber + for<'a> LookupSpan<'a>,
113{
114    let system_log = system_log?;
115    let format = fmt::format()
116        .without_time()
117        .with_target(false)
118        .with_level(false)
119        .with_ansi(false);
120    Some(
121        fmt::layer()
122            .with_writer(system_log.writer())
123            .with_ansi(false)
124            .event_format(RoleEventFormat {
125                run_mode,
126                inner: format,
127                timer: Some(LocalTime::rfc_3339()),
128                ansi: false,
129            }),
130    )
131}
132
133/// Structured journald logger for systemd environments, and the system log
134/// file beside it when `logging.yaml` declares one.
135pub fn journald_logger(
136    run_mode: RunMode,
137    system_log: Option<SystemLog>,
138) -> Result<(), Error> {
139    journald_logger_with_filter(
140        run_mode,
141        system_log,
142        env::var("RUST_LOG").ok().as_deref(),
143    )
144}
145
146/// Install journald logging with directives resolved by the process host.
147/// This entry does not read process env; absent or invalid directives use `info`.
148pub fn journald_logger_with_filter(
149    run_mode: RunMode,
150    system_log: Option<SystemLog>,
151    directives: Option<&str>,
152) -> Result<(), Error> {
153    let file = system_log_layer(run_mode, system_log);
154    let env_filter = resolved_filter(directives);
155
156    let jlayer = tracing_journald::layer()?.with_priority_mappings(
157        tracing_journald::PriorityMappings {
158            info: tracing_journald::Priority::Informational,
159            warn: tracing_journald::Priority::Warning,
160            error: tracing_journald::Priority::Error,
161            debug: tracing_journald::Priority::Debug,
162            trace: tracing_journald::Priority::Debug,
163        },
164    );
165
166    match run_mode {
167        RunMode::Standalone => {
168            tracing_subscriber::registry()
169                .with(env_filter)
170                .with(jlayer)
171                .with(file)
172                .init();
173        }
174        RunMode::Master | RunMode::Worker(_) => {
175            let role = run_mode.as_env_value();
176            let worker_id = run_mode
177                .worker_id()
178                .map_or_else(String::new, |id| id.to_string());
179
180            // `with_custom_fields` keeps values for the lifetime of the layer.
181            // Role is already static; only the numeric worker ID needs one
182            // bounded process-lifetime allocation.
183            let worker_id: &'static str = Box::leak(worker_id.into_boxed_str());
184            let jlayer = jlayer.with_custom_fields([
185                ("ROLE", role.as_bytes()),
186                ("WORKER_ID", worker_id.as_bytes()),
187            ]);
188            tracing_subscriber::registry()
189                .with(env_filter)
190                .with(jlayer)
191                .with(file)
192                .init();
193        }
194    }
195
196    Ok(())
197}
198/// Console logging for interactive or non-systemd runs, and the system log
199/// file beside it when `logging.yaml` declares one.
200pub fn console_logger(
201    run_mode: RunMode,
202    system_log: Option<SystemLog>,
203) -> Result<(), Error> {
204    console_logger_with_filter(
205        run_mode,
206        system_log,
207        env::var("RUST_LOG").ok().as_deref(),
208    )
209}
210
211/// Install console logging with directives resolved by the process host.
212/// Allows snapshot-owned `RUST_LOG` without populating libc's environment.
213pub fn console_logger_with_filter(
214    run_mode: RunMode,
215    system_log: Option<SystemLog>,
216    directives: Option<&str>,
217) -> Result<(), Error> {
218    let file = system_log_layer(run_mode, system_log);
219    let format = fmt::format()
220        .without_time()
221        .with_target(false)
222        .with_level(false)
223        .with_ansi(true);
224
225    let layer =
226        fmt::layer().with_writer(io::stdout).event_format(RoleEventFormat {
227            run_mode,
228            inner: format,
229            timer: Some(LocalTime::rfc_3339()),
230            ansi: true,
231        });
232
233    let env_filter = resolved_filter(directives);
234
235    tracing_subscriber::registry()
236        .with(env_filter)
237        .with(layer)
238        .with(file)
239        .init();
240
241    Ok(())
242}
243
244fn resolved_filter(directives: Option<&str>) -> EnvFilter {
245    directives
246        .and_then(|value| EnvFilter::try_new(value).ok())
247        .unwrap_or_else(|| EnvFilter::new("info"))
248}
249
250pub fn client_logger() -> Result<(), Error> {
251    let env_filter = EnvFilter::try_from_default_env()
252        .unwrap_or_else(|_| EnvFilter::new("info"));
253
254    let layer = fmt::layer().without_time().with_ansi(true).with_level(true);
255
256    tracing_subscriber::registry().with(env_filter).with(layer).init();
257
258    Ok(())
259}
260
261#[inline]
262pub fn is_running_under_systemd() -> bool {
263    env::var_os("JOURNAL_STREAM").is_some()
264        || env::var_os("INVOCATION_ID").is_some()
265}
266
267#[derive(thiserror::Error, Debug)]
268pub enum Error {
269    #[error("IO error: {0}")]
270    Io(#[from] io::Error),
271    #[error("logging configuration: {0}")]
272    Config(String),
273}