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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
// file : core/logger.c
// project : Salis-VM
// author : Paul Oliver <contact@pauloliver.dev>
// index:
// [section] includes
// [section] macros
// [section] definitions
// ----------------------------------------------------------------------------
// [section] includes
// ----------------------------------------------------------------------------
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include "logger.h"
// ----------------------------------------------------------------------------
// [section] macros
// ----------------------------------------------------------------------------
#define LOG_BUFFER_SIZE 0x800
#define COLOR_CLEAR "\033[0m"
#define COLOR_TRACE "\033[1;34m"
#define COLOR_INFO "\033[1;32m"
#define COLOR_ATTENTION "\033[1;33m"
#define LEVEL_TRACE "TRACE"
#define LEVEL_INFO "INFO"
#define LEVEL_ATTENTION "ATTENTION"
// ----------------------------------------------------------------------------
// [section] definitions
// ----------------------------------------------------------------------------
static void log_default(const char *color_code, const char *level, const char *format, va_list args) {
assert(level);
assert(format);
char log_buffer[LOG_BUFFER_SIZE];
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
int msec = (int)(ts.tv_nsec / 1000000l);
struct tm tm = *localtime(&ts.tv_sec);
pid_t pid = getpid();
int rem = snprintf(
log_buffer,
LOG_BUFFER_SIZE,
"\r%s%d-%02d-%02d %02d:%02d:%02d.%03d %07d [%s]%s ",
color_code ? color_code : "",
tm.tm_year + 1900,
tm.tm_mon + 1,
tm.tm_mday,
tm.tm_hour,
tm.tm_min,
tm.tm_sec,
msec,
pid,
level,
color_code ? COLOR_CLEAR : ""
);
vsnprintf(log_buffer + rem, LOG_BUFFER_SIZE - rem, format, args);
printf("%s\n", log_buffer);
fflush(stdout);
}
void log_trace(const char *format, ...) {
assert(format);
#if defined(LOG_TRACE)
va_list args;
va_start(args, format);
log_default(COLOR_TRACE, LEVEL_TRACE, format, args);
va_end(args);
#else
(void)format;
#endif
}
void log_info(const char *format, ...) {
assert(format);
va_list args;
va_start(args, format);
log_default(COLOR_INFO, LEVEL_INFO, format, args);
va_end(args);
}
void log_attention(const char *format, ...) {
assert(format);
va_list args;
va_start(args, format);
log_default(COLOR_ATTENTION, LEVEL_ATTENTION, format, args);
va_end(args);
}
|