chiark / gitweb /
[PATCH] klibc: strlcpy/strlcat - don't alter destination if size == 0
[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+5 must be < BUFLEN */
22
23 int __syslog_fd = -1;
24 static char id[MAXID+1];
25 static int syslog_flags = 0;
26
27 void openlog(const char *ident, int option, int facility)
28 {
29   int fd;
30
31   (void)option; (void)facility; /* Unused */
32   
33   if ( __syslog_fd == -1 ) {
34     __syslog_fd = fd = open(LOGDEV, O_WRONLY);
35     if ( fd == -1 )
36       return;
37     fcntl(fd, F_SETFD, (long)FD_CLOEXEC);
38   }
39   
40   syslog_flags = option;
41
42   strncpy(id, ident?ident:"", MAXID);
43 }
44
45 void vsyslog(int prio, const char *format, va_list ap)
46 {
47   char buf[BUFLEN];
48   int len;
49   int fd;
50
51   if ( __syslog_fd == -1 )
52     openlog(NULL, 0, 0);
53
54   buf[0] = '<';
55   buf[1] = LOG_PRI(prio)+'0';
56   buf[2] = '>';
57   len = 3;
58
59   if ( syslog_flags & LOG_PID )
60     len += sprintf(buf+3, "%s[%u]: ", id, getpid());
61   else if ( *id )
62     len += sprintf(buf+3, "%s: ", id);
63
64   len += vsnprintf(buf+len, BUFLEN-len, format, ap);
65
66   if ( len > BUFLEN-1 ) len = BUFLEN-1;
67   if (buf[len-1] != '\n')
68     buf[len++] = '\n';
69
70   fd = __syslog_fd;
71   if ( fd == -1 )
72     fd = 2;                     /* Failed to open log, write to stderr */
73
74   write(fd, buf, len);
75
76   if ( syslog_flags & LOG_PERROR )
77     _fwrite(buf+3, len-3, stderr);
78 }
79
80 void syslog(int prio, const char *format, ...)
81 {
82   va_list ap;
83
84   va_start(ap, format);
85   vsyslog(prio, format, ap);
86   va_end(ap);
87 }