-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathlog.c
84 lines (71 loc) · 1.86 KB
/
log.c
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
#include "log.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
static const char* LEVEL_NAMES[] = {"EN_PRINT_DEBUG", "EN_PRINT_INFO", "EN_PRINT_NOTICE", "EN_PRINT_WARN", "EN_PRINT_ERROR", "EN_PRINT_FATAL"};
static int enable_console = 1;
static FILE *log_stream = NULL;
static int log_level = EN_PRINT_INFO;
int configure_log(int lvl, const char* file, int use_console) {
FILE *stream = NULL;
int res = 0;
if (lvl > EN_PRINT_ERROR)
lvl = EN_PRINT_ERROR;
else if (lvl < EN_PRINT_DEBUG)
lvl = EN_PRINT_DEBUG;
log_level = lvl;
enable_console = use_console;
if (file != NULL) {
stream = fopen(file, "a");
if (stream == NULL) {
XL_DEBUG(EN_PRINT_ERROR, "Error opening log file");
res = 1;
} else {
log_stream = stream;
}
}
return res;
}
void destroy_log()
{
if (log_stream != NULL)
{
fclose(log_stream);
}
}
void logging(int lvl, const char *file, const char *func, const int line, const char *fmt, ...) {
va_list ap;
char buffer[512], *ptr = buffer;
int size, cap = 512;
time_t ts;
struct tm *tmp;
if (lvl < log_level) {
return;
}
ts = time(NULL);
tmp = localtime(&ts);
size = strftime(ptr, cap, "[%Y-%m-%d %H:%M:%S]", tmp);
ptr += size;
cap -= size;
size = snprintf(ptr, cap, "[%-5s][%s:%d][%s] ",
LEVEL_NAMES[lvl], file, line, func);
ptr += size;
cap -= size;
va_start(ap, fmt);
size = vsnprintf(ptr, cap, fmt, ap);
va_end(ap);
*(ptr + size) = '\n';
*(ptr + size + 1) = '\0';
if (enable_console) {
if (lvl >= EN_PRINT_WARN) {
fputs(buffer, stderr);
} else {
fputs(buffer, stdout);
}
}
if (log_stream != NULL) {
fputs(buffer, log_stream);
}
}