Files
cworker/logger.c
2023-08-16 01:01:16 +02:00

60 lines
1.3 KiB
C

/*
*
* Copyright 2023 Oleg Borodin <borodin@unix7.org>
*
*/
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdarg.h>
#define _CLOCK_SOURCE CLOCK_MONOTONIC
//#define CLOCK_SOURCE CLOCK_REALTIME_PRECISE
#define MAX_TS_LEN 256
void static set_timestamp(char* buffer) {
time_t now = time(NULL);
if (now < 0) {
return;
}
struct tm* ptm = localtime(&now);
if (ptm == NULL) {
return;
}
struct timespec tv;
clock_gettime(_CLOCK_SOURCE, &tv);
memset(buffer, '\0', MAX_TS_LEN);
sprintf(buffer, "%04d-%02d-%02dT%02d:%02d:%02d.%ld+%s",
ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour,
ptm->tm_min, ptm->tm_sec, tv.tv_nsec, ptm->tm_zone);
}
void log_error(const char* format, ...) {
char timestamp[MAX_TS_LEN];
set_timestamp(timestamp);
va_list args;
fprintf(stderr, "%s error: ", timestamp);
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
fprintf(stderr, "\n");
}
void log_debug(const char* format, ...) {
char timestamp[MAX_TS_LEN];
set_timestamp(timestamp);
va_list args;
fprintf(stderr, "%s debug: ", timestamp);
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
fprintf(stderr, "\n");
}