-
Notifications
You must be signed in to change notification settings - Fork 3
/
Logger.c
121 lines (97 loc) · 2.46 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
//
// Created by frank on 17-2-12.
//
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include <sys/time.h>
#include "Logger.h"
#define MAXLINE 256
const static char *log_level_str[] = {
"[DEBUG]",
"[INFO] ",
"[WARN] ",
"[ERROR]",
"[FATAL]"
};
#ifndef NDEBUG
int log_level = LOG_LEVEL_DEBUG;
#else
int log_level = LOG_LEVEL_INFO;
#endif
static int log_fd = STDOUT_FILENO;
static int timestamp(char *data, size_t len);
void set_log_level(int level)
{
if (level < LOG_LEVEL_DEBUG)
level = LOG_LEVEL_DEBUG;
if (level > LOG_LEVEL_FATAL)
level = LOG_LEVEL_FATAL;
log_level = level;
}
void set_log_fd(int fd)
{
if (fd <= 0)
fd = STDOUT_FILENO;
log_fd = fd;
}
void log_base(const char *file,
int line,
int level,
int to_abort,
const char *fmt, ...)
{
char data[MAXLINE];
size_t i = 0;
va_list ap;
i += timestamp(data, 32);
i += sprintf(data + i, " [%d]", getpid());
i += sprintf(data + i, " %s ", log_level_str[level]);
va_start(ap, fmt);
vsnprintf(data + i, MAXLINE - i, fmt, ap);
va_end(ap);
int err = dprintf(log_fd, "%s - %s:%d\n",
data, strrchr(file, '/') + 1, line);
if (err == -1) {
fprintf(stderr, "log failed");
}
if (to_abort) {
abort();
}
}
void log_sys(const char *file,
int line,
int to_abort,
const char *fmt, ...)
{
char data[MAXLINE];
size_t i = 0;
va_list ap;
i += timestamp(data, 32);
i += sprintf(data + i, " [%d]", getpid());
i += sprintf(data + i, " %s ", to_abort ? "[SYSFA]":"[SYSER]");
va_start(ap, fmt);
vsnprintf(data + i, MAXLINE - i, fmt, ap);
va_end(ap);
dprintf(log_fd, "%s: %s - %s:%d\n",
data, strerror(errno), strrchr(file, '/') + 1, line);
if (to_abort) {
abort();
}
}
static int timestamp(char *data, size_t len)
{
struct timeval tv;
gettimeofday(&tv, NULL);
time_t seconds = tv.tv_sec;
struct tm tm_time;
gmtime_r(&seconds, &tm_time);
return snprintf(data, len, "%4d%02d%02d %02d:%02d:%02d.%3ld",
tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday,
tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, tv.tv_usec / 1000);
}