From c7f3c47f9adf967f2886d066cfd0fb9e607864eb Mon Sep 17 00:00:00 2001 From: Lorenz Leutgeb Date: Tue, 29 Jul 2025 16:50:25 +0200 Subject: [PATCH] systemd: Add module for logging to the journal --- Cargo.lock | 14 ++++++++++++++ crates/radicle-systemd/Cargo.toml | 7 ++++++- crates/radicle-systemd/src/journal.rs | 23 +++++++++++++++++++++++ crates/radicle-systemd/src/lib.rs | 3 +++ 4 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 crates/radicle-systemd/src/journal.rs diff --git a/Cargo.lock b/Cargo.lock index cd21647f..401b1228 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2782,6 +2782,10 @@ dependencies = [ [[package]] name = "radicle-systemd" version = "0.9.0" +dependencies = [ + "log", + "systemd-journal-logger", +] [[package]] name = "radicle-term" @@ -3432,6 +3436,16 @@ dependencies = [ "syn 2.0.89", ] +[[package]] +name = "systemd-journal-logger" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7266304d24ca5a4b230545fc558c80e18bd3e1d2eb1be149b6bcd04398d3e79c" +dependencies = [ + "log", + "rustix 1.0.7", +] + [[package]] name = "tar" version = "0.4.40" diff --git a/crates/radicle-systemd/Cargo.toml b/crates/radicle-systemd/Cargo.toml index 1d233d97..549d39fb 100644 --- a/crates/radicle-systemd/Cargo.toml +++ b/crates/radicle-systemd/Cargo.toml @@ -8,6 +8,11 @@ edition.workspace = true version = "0.9.0" rust-version.workspace = true +[dependencies] +log = { workspace = true, optional = true } +systemd-journal-logger = { version = "2.2.2", optional = true } + [features] -default = ["listen"] +default = ["journal", "listen"] +journal = ["dep:log", "dep:systemd-journal-logger"] listen = [] \ No newline at end of file diff --git a/crates/radicle-systemd/src/journal.rs b/crates/radicle-systemd/src/journal.rs new file mode 100644 index 00000000..46d841d4 --- /dev/null +++ b/crates/radicle-systemd/src/journal.rs @@ -0,0 +1,23 @@ +use systemd_journal_logger::{connected_to_journal, current_exe_identifier, JournalLog}; + +/// If the current process is directly connected to the systemd journal, +/// return a logger that will write to it. +pub fn logger( + default_identifier: String, + extra_fields: I, +) -> std::io::Result>> +where + I: IntoIterator, + K: AsRef, + V: AsRef<[u8]>, +{ + if !connected_to_journal() { + return Ok(None); + } + + Ok(Some(Box::new( + JournalLog::new()? + .with_syslog_identifier(current_exe_identifier().unwrap_or(default_identifier)) + .with_extra_fields(extra_fields), + ))) +} diff --git a/crates/radicle-systemd/src/lib.rs b/crates/radicle-systemd/src/lib.rs index 039c9586..3e47b694 100644 --- a/crates/radicle-systemd/src/lib.rs +++ b/crates/radicle-systemd/src/lib.rs @@ -1,4 +1,7 @@ //! Library for interaction with systemd, specialized for Radicle. +#[cfg(feature = "journal")] +pub mod journal; + #[cfg(feature = "listen")] pub mod listen;