From e0ea43bf4e54b4cf993f7638a80b752fa3391c64 Mon Sep 17 00:00:00 2001 From: Egor Tensin Date: Thu, 8 Sep 2022 08:46:12 +0200 Subject: log: prepend timestamps --- src/log.h | 41 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/log.h b/src/log.h index 72a63c4..867919a 100644 --- a/src/log.h +++ b/src/log.h @@ -5,13 +5,44 @@ #include #include #include +#include +#include + +static inline void log_print_timestamp(FILE *dest) +{ + struct timeval tv; + struct tm tm; + char buf[64]; + size_t used = 0; + + if (gettimeofday(&tv, NULL) < 0) + return; + if (!gmtime_r(&tv.tv_sec, &tm)) + return; + + buf[0] = '\0'; + used += strftime(buf + used, sizeof(buf) - used, "[%F %T", &tm); + used += snprintf(buf + used, sizeof(buf) - used, ".%03ld] ", tv.tv_usec / 1000); + fprintf(dest, "%s", buf); +} #define CONCAT_INNER(a, b) a##b #define CONCAT(a, b) CONCAT_INNER(a, b) -#define print_errno(s) \ +static inline void log_prefix(FILE *dest) +{ + log_print_timestamp(dest); +} + +#define log_error_prefix() \ do { \ + log_prefix(stderr); \ fprintf(stderr, "%s(%d): ", basename(__FILE__), __LINE__); \ + } while (0) + +#define print_errno(s) \ + do { \ + log_error_prefix(); \ perror(s); \ } while (0) @@ -38,10 +69,14 @@ #define print_error(...) \ do { \ - fprintf(stderr, "%s(%d): ", basename(__FILE__), __LINE__); \ + log_error_prefix(); \ fprintf(stderr, __VA_ARGS__); \ } while (0) -#define print_log(...) printf(__VA_ARGS__) +#define print_log(...) \ + do { \ + log_prefix(stdout); \ + printf(__VA_ARGS__); \ + } while (0) #endif -- cgit v1.2.3