2 #include <sys/socket.h>
16 static char log_ident[32];
18 static int log_facility = LOG_USER;
19 static int log_mask = 0xff;
20 static int log_fd = -1;
22 int setlogmask(int maskpri)
24 if (maskpri) return a_swap(&log_mask, maskpri);
39 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
44 pthread_setcancelstate(cs, 0);
47 static void __openlog()
49 int fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
51 if (connect(fd, (void *)&log_addr, sizeof log_addr) < 0)
57 void openlog(const char *ident, int opt, int facility)
60 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
64 size_t n = strnlen(ident, sizeof log_ident - 1);
65 memcpy(log_ident, ident, n);
71 log_facility = facility;
73 if ((opt & LOG_NDELAY) && log_fd<0) __openlog();
76 pthread_setcancelstate(cs, 0);
79 static void _vsyslog(int priority, const char *message, va_list ap)
85 int errno_save = errno;
91 if (log_fd < 0) __openlog();
93 if (!(priority & LOG_FACMASK)) priority |= log_facility;
97 strftime(timebuf, sizeof timebuf, "%b %e %T", &tm);
99 pid = (log_opt & LOG_PID) ? getpid() : 0;
100 l = snprintf(buf, sizeof buf, "<%d>%s %n%s%s%.0d%s: ",
101 priority, timebuf, &hlen, log_ident, "["+!pid, pid, "]"+!pid);
103 l2 = vsnprintf(buf+l, sizeof buf - l, message, ap);
105 if (l2 >= sizeof buf - l) l = sizeof buf - 1;
107 if (buf[l-1] != '\n') buf[l++] = '\n';
108 if (send(log_fd, buf, l, 0) < 0 && (log_opt & LOG_CONS)) {
109 fd = open("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
111 dprintf(fd, "%.*s", l-hlen, buf+hlen);
115 if (log_opt & LOG_PERROR) dprintf(2, "%.*s", l-hlen, buf+hlen);
119 void __vsyslog(int priority, const char *message, va_list ap)
122 if (!(log_mask & LOG_MASK(priority&7)) || (priority&~0x3ff)) return;
123 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
125 _vsyslog(priority, message, ap);
127 pthread_setcancelstate(cs, 0);
130 void syslog(int priority, const char *message, ...)
133 va_start(ap, message);
134 __vsyslog(priority, message, ap);
138 weak_alias(__vsyslog, vsyslog);