-
Notifications
You must be signed in to change notification settings - Fork 110
/
LibeventLog.cpp
executable file
·104 lines (82 loc) · 1.88 KB
/
LibeventLog.cpp
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
99
100
101
102
103
104
#include "LibeventLog.h"
#include <time.h>
static FILE *logfile = NULL;
LibeventLog::LibeventLog(void)
{
logfile = NULL;
}
LibeventLog::~LibeventLog(void)
{
fclose(logfile);
}
void write_to_file_fatal_cb(int err) {
if (logfile == NULL) {
return;
}
fprintf(logfile, "[**** fatal error ****] %d\n", err);
}
static void discard_log(int severity, const char *msg) {
}
static void write_to_file_cv(int severity, const char *msg) {
const char *s;
if (logfile == NULL) {
return;
}
switch (severity) {
case _EVENT_LOG_DEBUG:
s = "debug";
break;
case _EVENT_LOG_MSG:
s = "msg";
break;
case _EVENT_LOG_WARN:
s = "warn";
break;
case _EVENT_LOG_ERR:
s = "error";
break;
default:
s = "?";
break;
}
fprintf(logfile, "[%s] %s\n", s, msg);
fflush(logfile);
}
void LibeventLog::turnOn(const char *filepath) {
if (logfile != NULL) {
event_set_log_callback(write_to_file_cv);
return;
}
logfile = fopen(filepath, "a+");
if (logfile == NULL) {
event_set_log_callback(discard_log);
} else {
event_set_log_callback(write_to_file_cv);
}
event_set_fatal_callback(write_to_file_fatal_cb);
}
void LibeventLog::turnOff() {
event_set_log_callback(discard_log);
fclose(logfile);
logfile = NULL;
}
void LibeventLog::userLog(const char *fmt, ...) {
if (logfile == NULL) {
return;
}
va_list ap;
char buf[LOG_TEMP_BUFFER_SIZE];
memset(buf, 0, sizeof(buf));
time_t now;
struct tm *curtime = NULL;
time(&now);
curtime = localtime(&now);
sprintf(buf, "[%d-%02d-%02d %02d:%02d:%02d] ", (curtime->tm_year+1900), (curtime->tm_mon+1), curtime->tm_mday,
curtime->tm_hour, curtime->tm_min, curtime->tm_sec);
int len = strlen(buf);
va_start(ap, fmt);
vsnprintf(buf+len, LOG_TEMP_BUFFER_SIZE-len-1, fmt, ap);
va_end(ap);
fprintf(logfile, "%s\n", buf);
fflush(logfile);
}