1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
/*
* Copyright (c) 2023 Egor Tensin <Egor.Tensin@gmail.com>
* This file is part of the "cimple" project.
* For details, see https://github.com/egor-tensin/cimple.
* Distributed under the MIT License.
*/
#include "log.h"
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
int g_log_lvl = LOG_LVL_INFO;
static inline void log_prefix_timestamp(FILE *dest)
{
struct timeval tv;
struct tm tm;
char buf[64];
size_t used = 0;
if (gettimeofday(&tv, NULL) < 0)
return;
if (!gmtime_r(&tv.tv_sec, &tm))
return;
buf[0] = '\0';
used += strftime(buf + used, sizeof(buf) - used, "%F %T", &tm);
used += snprintf(buf + used, sizeof(buf) - used, ".%03ld | ", tv.tv_usec / 1000);
fprintf(dest, "%s", buf);
}
static inline void log_prefix_thread_id(FILE *dest)
{
fprintf(dest, "%d | ", gettid());
}
int log_entry_start(int lvl, FILE *dest)
{
if (lvl < g_log_lvl)
return 0;
flockfile(dest);
log_prefix_timestamp(dest);
log_prefix_thread_id(dest);
return 1;
}
void log_entry_end(FILE *dest)
{
funlockfile(dest);
}
|