-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.c
95 lines (82 loc) · 2.01 KB
/
logger.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
85
86
87
88
89
90
91
92
93
94
95
#include <time.h>
#include <errno.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "conf.h"
#include "logger.h"
FILE *log_open(const char *path) {
FILE *fp;
char *lvl;
lvl = dconf_get_str("log.level", 0);
/*
* parse the debug level
*/
if (!strcasecmp(lvl, "debug"))
conf.log_level = LOG_DEBUG;
else if (!strcasecmp(lvl, "info"))
conf.log_level = LOG_INFO;
else if (!strcasecmp(lvl, "hack"))
conf.log_level = LOG_HACK;
else if (!strcasecmp(lvl, "warning"))
conf.log_level = LOG_WARNING;
else if (!strcasecmp(lvl, "error"))
conf.log_level = LOG_ERROR;
else if (!strcasecmp(lvl, "fatal"))
conf.log_level = LOG_FATAL;
if ((fp = fopen(path, "w")) == NULL) {
Log(LOG_ERROR, "Unable to open log file %s: %d (%s)", path, errno, strerror(errno));
return NULL;
}
return fp;
}
void log_close(FILE * fp) {
if (fp != NULL) {
fclose(fp);
fp = NULL;
}
}
void Log(enum log_priority priority, const char *fmt, ...) {
va_list ap;
char timestamp[64];
time_t t;
struct tm *tm;
char *level = NULL;
if (priority < conf.log_level) {
return;
}
if (!conf.log_fp)
conf.log_fp = stdout;
va_start(ap, fmt);
t = time(NULL);
tm = localtime(&t);
switch (priority) {
case LOG_DEBUG:
level = "debug";
break;
case LOG_INFO:
level = "info";
break;
case LOG_WARNING:
level = "warning";
break;
case LOG_ERROR:
level = "error";
break;
case LOG_FATAL:
level = "critical";
break;
case LOG_HACK:
level = "hack";
break;
default:
level = "unknown";
break;
}
strftime(timestamp, sizeof(timestamp) - 1, "%Y/%m/%d %H:%M:%S", tm);
fprintf(conf.log_fp, "[%s] %s: ", timestamp, level);
vfprintf(conf.log_fp, fmt, ap);
fprintf(conf.log_fp, "\n");
fflush(conf.log_fp);
va_end(ap);
}