forked from aarond10/https_dns_proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.c
More file actions
76 lines (65 loc) · 1.51 KB
/
logging.c
File metadata and controls
76 lines (65 loc) · 1.51 KB
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
#include <sys/time.h>
#include <sys/types.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "logging.h"
static FILE *logf = NULL;
static int loglevel = LOG_ERROR;
// Renders a severity as a short string.
static const char *SeverityStr(int severity) {
switch (severity) {
case LOG_DEBUG:
return "[D]";
case LOG_INFO:
return "[I]";
case LOG_WARNING:
return "[W]";
case LOG_ERROR:
return "[E]";
case LOG_FATAL:
return "[F]";
default:
fprintf(logf, "Unknown log severity: %d\n", severity);
exit(EXIT_FAILURE);
}
}
void logging_init(int fd, int level) {
if (logf)
fclose(logf);
logf = fdopen(fd, "a");
loglevel = level;
}
void logging_cleanup() {
if (logf)
fclose(logf);
logf = NULL;
}
void _log(const char *file, int line, int severity, const char *fmt, ...) {
if (severity < loglevel)
return;
if (!logf)
logf = fdopen(STDOUT_FILENO, "w");
// We just want to log the filename, not the path.
const char *filename = file + strlen(file);
while (filename > file && *filename != '/') {
filename--;
}
if (*filename == '/')
filename++;
struct timeval tv;
gettimeofday(&tv, NULL);
fprintf(logf, "%s %8ld.%06ld %s:%d ", SeverityStr(severity), tv.tv_sec,
tv.tv_usec, filename, line);
va_list args;
va_start(args, fmt);
vfprintf(logf, fmt, args);
va_end(args);
fprintf(logf, "\n");
if (severity >= LOG_WARNING)
fflush(logf);
if (severity == LOG_FATAL)
exit(1);
}