Skip to content

Commit

Permalink
logger: Fix gmtime usage for Windows
Browse files Browse the repository at this point in the history
Signed-off-by: Siddharth Chandrasekaran <[email protected]>
  • Loading branch information
sidcha committed Mar 9, 2024
1 parent eb9e9e5 commit 9270027
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 16 deletions.
2 changes: 2 additions & 0 deletions include/utils/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
6 changes: 1 addition & 5 deletions src/logger.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
41 changes: 30 additions & 11 deletions src/utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -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 <sys/time.h>
#include <time.h>
#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()
{
Expand All @@ -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;
Expand Down

0 comments on commit 9270027

Please sign in to comment.