Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Timestamp log entries with millisecond resolution
  • Loading branch information
LavaLit committed Jan 31, 2024
commit 2e9a6275ae2a2e3525b04f34f536de31d7e801dd
14 changes: 12 additions & 2 deletions lib/log/src/log.c
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <stdatomic.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>

#define get_filename(file) (strrchr(file, '/') ? strrchr(file, '/') + 1 : file)
Expand Down Expand Up @@ -78,10 +79,19 @@ int log_printf(const char *file, const char *func, int line, const int level, co
va_end(args2);
static char buffer[1024];

int bytes =
// Timestamp
struct timeval now;
gettimeofday(&now, NULL);
int milli = now.tv_usec / 1000;
char timestamp[sizeof "YYYY-MM-DD HH:MM:SS.sss"];
int bytes = strftime(timestamp, sizeof timestamp, "%F %T.", gmtime(&now.tv_sec));
snprintf(&timestamp[bytes], sizeof(timestamp) - bytes, "%03d", milli);

bytes =
snprintf(buffer,
sizeof(buffer),
"[%s][%s:%s:%d] %s\r\n",
"%s [%s][%s:%s:%d] %s\r\n",
timestamp,
log_level_names[level + 2],
get_filename(file),
func,
Expand Down