common/log: improve time prefix

Same as [1].

[1]: https://github.com/swaywm/wlroots/pull/2052
This commit is contained in:
Simon Ser 2020-03-05 13:54:28 +01:00 committed by Drew DeVault
parent a2d49099e1
commit e81d9fde66
1 changed files with 30 additions and 8 deletions

View File

@ -36,6 +36,7 @@ bool _sway_assert(bool condition, const char *format, ...) {
static bool colored = true;
static sway_log_importance_t log_importance = SWAY_ERROR;
static struct timespec start_time = {-1, -1};
static const char *verbosity_colors[] = {
[SWAY_SILENT] = "",
@ -44,20 +45,39 @@ static const char *verbosity_colors[] = {
[SWAY_DEBUG ] = "\x1B[1;30m",
};
static void timespec_sub(struct timespec *r, const struct timespec *a,
const struct timespec *b) {
const long NSEC_PER_SEC = 1000000000;
r->tv_sec = a->tv_sec - b->tv_sec;
r->tv_nsec = a->tv_nsec - b->tv_nsec;
if (r->tv_nsec < 0) {
r->tv_sec--;
r->tv_nsec += NSEC_PER_SEC;
}
}
static void init_start_time(void) {
if (start_time.tv_sec >= 0) {
return;
}
clock_gettime(CLOCK_MONOTONIC, &start_time);
}
static void sway_log_stderr(sway_log_importance_t verbosity, const char *fmt,
va_list args) {
init_start_time();
if (verbosity > log_importance) {
return;
}
// prefix the time to the log message
struct tm result;
time_t t = time(NULL);
struct tm *tm_info = localtime_r(&t, &result);
char buffer[26];
// generate time prefix
strftime(buffer, sizeof(buffer), "%F %T - ", tm_info);
fprintf(stderr, "%s", buffer);
struct timespec ts = {0};
clock_gettime(CLOCK_MONOTONIC, &ts);
timespec_sub(&ts, &ts, &start_time);
fprintf(stderr, "%02d:%02d:%02d.%03ld ", (int)(ts.tv_sec / 60 / 60),
(int)(ts.tv_sec / 60 % 60), (int)(ts.tv_sec % 60),
ts.tv_nsec / 1000000);
unsigned c = (verbosity < SWAY_LOG_IMPORTANCE_LAST) ? verbosity :
SWAY_LOG_IMPORTANCE_LAST - 1;
@ -75,6 +95,8 @@ static void sway_log_stderr(sway_log_importance_t verbosity, const char *fmt,
}
void sway_log_init(sway_log_importance_t verbosity, terminate_callback_t callback) {
init_start_time();
if (verbosity < SWAY_LOG_IMPORTANCE_LAST) {
log_importance = verbosity;
}