-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.c
More file actions
89 lines (79 loc) · 1.78 KB
/
logger.c
File metadata and controls
89 lines (79 loc) · 1.78 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
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
* A simplified implementation of logger(1)
* ./logger [-l level] message
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
#include <errno.h>
#define NLEVEL 8
static const char *const LEVELS[NLEVEL] = {
"emergency", "alert", "critical", "error", "warning", "notice", "info", "debug"
};
static const int LEVEL[NLEVEL] = {
LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG
};
static void exit_usage() {
puts("./logger [-l emergency|alert|critical|error|warning|notice|info|debug]"\
" message");
exit(EXIT_FAILURE);
}
static void exit_error() {
printf("logger: %s\n", strerror(errno));
exit(errno);
}
static char *catargv(int argc, int argoff, char **argv) {
char *msg;
int i, cursor, mlen;
for (i = argoff, mlen = 0; i < argc; i++)
mlen += strlen(argv[i]) + 1;
msg = malloc(mlen == 0 ? 1 : mlen);
msg[0] = '\0';
for (i = optind, cursor = 0; i < argc; i++) {
mlen = strlen(argv[i]);
cursor += mlen + 1;
strncat(msg, argv[i], mlen);
msg[cursor - 1] = ' ';
msg[cursor] = '\0';
}
return msg;
}
int main(int argc, char **argv) {
int ch, level, i;
char *levels, *msg;
levels = NULL;
while ((ch = getopt(argc, argv, "l:")) != -1) {
switch (ch) {
case 'l':
levels = optarg;
break;
case '?':
exit_usage();
default:
break;
}
}
if (levels != NULL && argc < 3)
exit_usage();
else if (argc < 2)
exit_usage();
if ((msg = catargv(argc, optind, argv)) == NULL)
exit_error();
if (levels != NULL) {
for (i = 0; i < NLEVEL; i++) {
if (strncmp(LEVELS[i], levels, strlen(levels) + 1) == 0) {
level = LEVEL[i];
break;
}
}
if (i == NLEVEL)
exit_usage();
} else {
level = LOG_INFO;
}
syslog(LOG_LOCAL0|level, "%s", msg);
free(msg);
exit(EXIT_SUCCESS);
}