chiark / gitweb /
more fixups
[elogind.git] / klibc / klibc / syslog.c
1 /*
2  * syslog.c
3  *
4  * Issue syslog messages via the kernel printk queue.
5  */
6
7 #include <stdio.h>
8 #include <string.h>
9 #include <stdarg.h>
10 #include <syslog.h>
11 #include <unistd.h>
12 #include <fcntl.h>
13
14 /* Maximum size for a kernel message */
15 #define BUFLEN 1024
16
17 /* Logging node */
18 #define LOGDEV "/dev/kmsg"
19
20 /* Max length of ID string */
21 #define MAXID 31                /* MAXID+6 must be < BUFLEN */
22
23 int __syslog_fd = -1;
24 static char id[MAXID+1];
25
26 void openlog(const char *ident, int option, int facility)
27 {
28   int fd;
29
30   (void)option; (void)facility; /* Unused */
31   
32   if ( __syslog_fd == -1 ) {
33     __syslog_fd = fd = open(LOGDEV, O_WRONLY);
34     if ( fd == -1 )
35       return;
36     fcntl(fd, F_SETFD, (long)FD_CLOEXEC);
37   }
38   
39   strncpy(id, ident?ident:"", MAXID);
40   id[MAXID] = '\0';             /* Make sure it's null-terminated */
41 }
42
43 void vsyslog(int prio, const char *format, va_list ap)
44 {
45   char buf[BUFLEN];
46   int len;
47   int fd;
48
49   if ( __syslog_fd == -1 )
50     openlog(NULL, 0, 0);
51
52   buf[0] = '<';
53   buf[1] = LOG_PRI(prio)+'0';
54   buf[2] = '>';
55   len = 3;
56
57   if ( *id )
58     len += sprintf(buf+3, "%s: ", id);
59
60   len += vsnprintf(buf+len, BUFLEN-len, format, ap);
61
62   if ( len > BUFLEN-1 ) len = BUFLEN-1;
63   if (buf[len-1] != '\n')
64     buf[len++] = '\n';
65
66   fd = __syslog_fd;
67   if ( fd == -1 )
68     fd = 2;                     /* Failed to open log, write to stderr */
69
70   write(fd, buf, len);
71 }
72
73 void syslog(int prio, const char *format, ...)
74 {
75   va_list ap;
76
77   va_start(ap, format);
78   vsyslog(prio, format, ap);
79   va_end(ap);
80 }