]> git.ipfire.org Git - pakfire.git/commitdiff
logging: Log to journald when available
authorMichael Tremer <michael.tremer@ipfire.org>
Thu, 1 Jul 2021 12:24:16 +0000 (12:24 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Thu, 1 Jul 2021 12:26:38 +0000 (12:26 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/libpakfire/logging.c

index cbc559db5593ce82b47e6debc1b61d509f7b7cb7..75182ffa6e353c6c7e414a0cb041baaca552e9d8 100644 (file)
 #                                                                             #
 #############################################################################*/
 
+#include <errno.h>
 #include <stdarg.h>
 #include <stdio.h>
-#include <syslog.h>
+#include <stdlib.h>
 
 #include <pakfire/private.h>
 
+#ifdef HAVE_SYSTEMD
+#include <systemd/sd-journal.h>
+#else
+#include <syslog.h>
+#endif
+
 PAKFIRE_EXPORT void pakfire_log_stderr(void* data, int priority, const char* file,
                int line, const char* fn, const char* format, va_list args) {
        fprintf(stderr, "pakfire: ");
@@ -35,8 +42,50 @@ PAKFIRE_EXPORT void pakfire_log_stderr(void* data, int priority, const char* fil
        vfprintf(stderr, format, args);
 }
 
+#ifdef HAVE_SYSTEMD
+
+PAKFIRE_EXPORT void pakfire_log_syslog(void* data, int priority, const char* file,
+               int line, const char* fn, const char* format, va_list args) {
+
+       char* buffer = NULL;
+       int r;
+
+       // Format log message
+       r = vasprintf(&buffer, format, args);
+       if (r < 0)
+               return;
+
+       // Send message to journald
+       r = sd_journal_send(
+               "MESSAGE=%s", buffer,
+               "PRIORITY=%d", priority,
+
+               // Syslog compat
+               "SYSLOG_IDENTIFIER=pakfire",
+
+               // Debugging stuff
+               "ERRNO=%d", errno,
+               "CODE_FILE=%s", file,
+               "CODE_LINE=%d", line,
+               "CODE_FUNC=%s", fn,
+
+               NULL
+       );
+
+       // Fall back to standard output
+       if (r)
+               sd_journal_perror(buffer);
+
+       // Cleanup
+       free(buffer);
+}
+
+#else /* HAVE_SYSTEMD */
+
 PAKFIRE_EXPORT void pakfire_log_syslog(void* data, int priority, const char* file,
                int line, const char* fn, const char* format, va_list args) {
        openlog("pakfire", LOG_PID, LOG_DAEMON);
        vsyslog(priority | LOG_DAEMON, format, args);
 }
+
+#endif /* HAVE_SYSTEMD */