From 9270027d89fe918623b6b9fa26790e9356e8039b Mon Sep 17 00:00:00 2001 From: Siddharth Chandrasekaran Date: Sat, 9 Mar 2024 03:14:20 +0100 Subject: [PATCH] logger: Fix gmtime usage for Windows Signed-off-by: Siddharth Chandrasekaran --- include/utils/utils.h | 2 ++ src/logger.c | 6 +----- src/utils.c | 41 ++++++++++++++++++++++++++++++----------- 3 files changed, 33 insertions(+), 16 deletions(-) diff --git a/include/utils/utils.h b/include/utils/utils.h index 681f749..ce891df 100644 --- a/include/utils/utils.h +++ b/include/utils/utils.h @@ -138,6 +138,8 @@ extern "C" { #define __unreachable() #define likely(p) (p) #define unlikely(p) (p) +#define isatty _isatty +#define fileno _fileno #else #define __format_printf(x, y) __attribute__((format(printf, x, y))) #define __noreturn __attribute__((noreturn)) diff --git a/src/logger.c b/src/logger.c index 2e9a48a..d0c7ec0 100644 --- a/src/logger.c +++ b/src/logger.c @@ -80,11 +80,7 @@ static const char *get_rel_path(logger_t *ctx, const char *abs_path) static const char *get_tstamp() { static char time_buf[24]; - struct tm gmt; - time_t now = time(NULL); - - gmtime_r(&now, &gmt); - strftime(time_buf, sizeof(time_buf), "%Y-%m-%dT%H:%M:%S", &gmt); + add_iso8601_utc_datetime(time_buf, sizeof(time_buf)); return time_buf; } diff --git a/src/utils.c b/src/utils.c index 72e3147..85d817a 100644 --- a/src/utils.c +++ b/src/utils.c @@ -117,10 +117,38 @@ int gettimeofday(struct timeval * tp, struct timezone * tzp) tp->tv_usec = (long) (system_time.wMilliseconds * 1000); return 0; } -#else + +int add_iso8601_utc_datetime(char* buf, size_t size) +{ + int r; + SYSTEMTIME utcTime; + GetSystemTime(&utcTime); // Get the current UTC time + + // Format: YYYY-MM-DDThh:mm:ssZ + r = snprintf(buf, size, "%04d-%02d-%02dT%02d:%02d:%02dZ", + utcTime.wYear, utcTime.wMonth, utcTime.wDay, + utcTime.wHour, utcTime.wMinute, utcTime.wSecond); + return r; +} + +#else /* WINDOWS */ + #include #include -#endif + +int add_iso8601_utc_datetime(char *buf, size_t size) +{ + time_t now; + struct tm timeinfo; + + // Format: YYYY-MM-DDThh:mm:ssZ + time(&now); + gmtime_s(&timeinfo, &now); + + return strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", &timeinfo); +} + +#endif /* WINDOWS */ int64_t usec_now() { @@ -142,15 +170,6 @@ void get_time(uint32_t *seconds, uint32_t *micro_seconds) *micro_seconds = tv.tv_usec; } -int add_iso8601_utc_datetime(char *buf, size_t size) -{ - time_t now; - - // Format: YYYY-MM-DDThh:mm:ssZ - time(&now); - return strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", gmtime(&now)); -} - int64_t usec_since(int64_t last) { return usec_now() - last;