From a2a979ea2e7ded82cbe4d4cab5da6e613d74a9d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C5=99emysl=20Janouch?= Date: Tue, 15 Jul 2014 22:23:53 +0200 Subject: Make it possible to route messages to syslog --- src/common.c | 51 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 12 deletions(-) (limited to 'src/common.c') diff --git a/src/common.c b/src/common.c index 8f7ffd1..800aea5 100644 --- a/src/common.c +++ b/src/common.c @@ -42,6 +42,7 @@ #include #include #include +#include #include #include @@ -86,28 +87,54 @@ extern char **environ; #define BLOCK_START do { #define BLOCK_END } while (0) -// --- Utilities --------------------------------------------------------------- +// --- Logging ----------------------------------------------------------------- static void -print_message (FILE *stream, const char *type, const char *fmt, ...) - ATTRIBUTE_PRINTF (3, 4); +log_message_syslog (int prio, const char *quote, const char *fmt, va_list ap) +{ + va_list va; + va_copy (va, ap); + int size = vsnprintf (NULL, 0, fmt, va); + va_end (va); + if (size < 0) + return; + + char buf[size + 1]; + if (vsnprintf (buf, sizeof buf, fmt, ap) >= 0) + syslog (prio, "%s%s", quote, buf); +} static void -print_message (FILE *stream, const char *type, const char *fmt, ...) +log_message_stdio (int prio, const char *quote, const char *fmt, va_list ap) { - va_list ap; + (void) prio; + FILE *stream = stderr; - va_start (ap, fmt); - fprintf (stream, "%s ", type); + fputs (quote, stream); vfprintf (stream, fmt, ap); fputs ("\n", stream); +} + +static void (*g_log_message_real) (int, const char *, const char *, va_list) + = log_message_stdio; + +static void +log_message (int priority, const char *quote, const char *fmt, ...) + ATTRIBUTE_PRINTF (3, 4); + +static void +log_message (int priority, const char *quote, const char *fmt, ...) +{ + va_list ap; + va_start (ap, fmt); + g_log_message_real (priority, quote, fmt, ap); va_end (ap); } -#define print_fatal(...) print_message (stderr, "fatal:", __VA_ARGS__) -#define print_error(...) print_message (stderr, "error:", __VA_ARGS__) -#define print_warning(...) print_message (stderr, "warning:", __VA_ARGS__) -#define print_status(...) print_message (stdout, "--", __VA_ARGS__) +#define print_fatal(...) log_message (LOG_ERR, "fatal: ", __VA_ARGS__) +#define print_error(...) log_message (LOG_ERR, "error: ", __VA_ARGS__) +#define print_warning(...) log_message (LOG_WARNING, "warning: ", __VA_ARGS__) +#define print_status(...) log_message (LOG_INFO, "-- ", __VA_ARGS__) // --- Debugging and assertions ------------------------------------------------ @@ -122,7 +149,7 @@ static bool g_soft_asserts_are_deadly; ///< soft_assert() aborts as well #define print_debug(...) \ BLOCK_START \ if (g_debug_mode) \ - print_message (stderr, "debug:", __VA_ARGS__); \ + log_message (LOG_DEBUG, "debug: ", __VA_ARGS__); \ BLOCK_END static void -- cgit v1.2.3