bootc_lib/
journal.rs

1//! Thin wrapper for systemd journaling; these APIs are no-ops
2//! when not running under systemd.  Only use them when
3
4use std::collections::HashMap;
5use std::sync::atomic::{AtomicBool, Ordering};
6
7/// Set to true if we failed to write to the journal once
8static EMITTED_JOURNAL_ERROR: AtomicBool = AtomicBool::new(false);
9
10/// Wrapper for structured logging which is an explicit no-op
11/// when systemd is not in use (e.g. in a container).
12pub(crate) fn journal_send<K, V>(
13    priority: libsystemd::logging::Priority,
14    msg: &str,
15    vars: impl Iterator<Item = (K, V)>,
16) where
17    K: AsRef<str>,
18    V: AsRef<str>,
19{
20    if !libsystemd::daemon::booted() {
21        return;
22    }
23    if let Err(e) = libsystemd::logging::journal_send(priority, msg, vars) {
24        if !EMITTED_JOURNAL_ERROR.swap(true, Ordering::SeqCst) {
25            eprintln!("failed to write to journal: {e}");
26        }
27    }
28}
29
30/// Wrapper for writing to systemd journal which is an explicit no-op
31/// when systemd is not in use (e.g. in a container).
32#[allow(dead_code)]
33pub(crate) fn journal_print(priority: libsystemd::logging::Priority, msg: &str) {
34    let vars: HashMap<&str, &str> = HashMap::new();
35    journal_send(priority, msg, vars.into_iter())
36}