Merge pull request #4553 from VannTen/feat/native_journal_log

log: use native journald protocol for when running as a service
This commit is contained in:
Alexis Rouillard
2026-07-04 00:30:26 +02:00
committed by GitHub
2 changed files with 58 additions and 1 deletions
+53 -1
View File
@@ -7,6 +7,17 @@
#include <list>
#include <mutex>
#ifdef HAVE_LIBSYSTEMD
#include <spdlog/sinks/systemd_sink.h>
#include <sys/stat.h>
#include <cassert>
#include <charconv>
#include <cstddef>
#include <cstdlib>
#include <system_error>
#endif
#include "bar.hpp"
#include "client.hpp"
#include "util/SafeSignal.hpp"
@@ -129,7 +140,7 @@ static void handleSignalMainThread(int signum, bool& reload) {
return;
}
#endif
switch (signum) {
case SIGUSR1:
handleUserSignal(SIGUSR1, reload);
@@ -162,7 +173,48 @@ static void handleSignalMainThread(int signum, bool& reload) {
}
}
static void logToJournalIfRunAsService() {
#ifdef HAVE_LIBSYSTEMD
/* Implementation of automatic protocol upgrading (from stderr to journal)
** as described in https://systemd.io/JOURNAL_NATIVE_PROTOCOL */
char const* journal_stream = std::getenv("JOURNAL_STREAM");
if (journal_stream != nullptr) {
dev_t device;
ino_t inode;
size_t len = std::strlen(journal_stream);
auto result = std::from_chars(journal_stream, journal_stream + len, device);
if (result.ec == std::errc{})
result = std::from_chars(result.ptr + 1, journal_stream + len, inode);
if (result.ec != std::errc{}) {
spdlog::warn("malformed JOURNAL_STREAM (\"{}\"): {}, logging to console", journal_stream,
std::make_error_condition(result.ec).message());
}
struct stat f_stderr;
if (fstat(STDERR_FILENO, &f_stderr) != 0) {
spdlog::warn("unable to check stderr device and inode numbers: {}", strerror(errno));
} else if (device == f_stderr.st_dev && inode == f_stderr.st_ino) {
auto journald = spdlog::systemd_logger_st("native_journal", "waybar", false);
/* systemd_logger_st is thread-safe with enable_formatter = false
** thanks to underlying sd_journal_send being thread-safe
** https://github.com/gabime/spdlog/issues/2320#issuecomment-1079766037
*/
spdlog::set_default_logger(journald);
} else {
spdlog::info("JOURNAL_STREAM does not point to stderr, logging to console");
}
} else {
spdlog::info("no JOURNAL_STREAM, logging to console");
}
#endif
}
int main(int argc, char* argv[]) {
logToJournalIfRunAsService();
try {
auto* client = waybar::Client::inst();