-
Notifications
You must be signed in to change notification settings - Fork 14
/
log.c
80 lines (65 loc) · 1.49 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
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
#include "log.h"
const static char *logname;
static int loglevel = LOG_INFO;
int use_syslog = 0;
void startlog(const char *ident)
{
if (use_syslog) {
openlog(ident, LOG_PID, LOG_USER);
setlogmask(LOG_UPTO(loglevel));
} else {
logname = ident;
}
}
void mylog(int priority, const char *message, ...)
{
va_list ap;
if (use_syslog) {
va_start(ap, message);
vsyslog(priority, message, ap);
va_end(ap);
} else {
if (priority > loglevel) {
return;
}
time_t t = time(NULL);
char tmp[256];
memset((void *) tmp, 0, sizeof(tmp));
char *loglevel;
switch (priority) {
case LOG_ERR:
loglevel = "ERROR";
break;
case LOG_WARNING:
loglevel = "WARNING";
break;
case LOG_INFO:
loglevel = "INFO";
break;
case LOG_DEBUG:
default:
loglevel = "DEBUG";
break;
}
sprintf(tmp, "[%lu] %s[%d]: %s: ", t, logname, getpid(), loglevel);
char out[strlen(tmp) + strlen(message) + 1];
strcpy(out, tmp);
strcat(out, message);
strcat(out, "\n");
va_start(ap, message);
vfprintf(stderr, out, ap);
va_end(ap);
}
}
void endlog(void)
{
if (use_syslog) {
closelog();
}
}