2 * ulog - simple logging functions
4 * Copyright (C) 2015 Jo-Philipp Wich <jow@openwrt.org>
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
27 static int _ulog_channels = -1;
28 static int _ulog_facility = -1;
29 static int _ulog_threshold = LOG_DEBUG;
30 static int _ulog_initialized = 0;
31 static const char *_ulog_ident = NULL;
33 static const char *ulog_default_ident(void)
39 if ((self = fopen("/proc/self/status", "r")) != NULL) {
40 while (fgets(line, sizeof(line), self)) {
41 if (!strncmp(line, "Name:", 5)) {
43 p = strtok(NULL, "\t\n");
53 static void ulog_defaults(void)
57 if (_ulog_initialized)
60 env = getenv("PREINIT");
62 if (_ulog_channels < 0) {
63 if (env && !strcmp(env, "1"))
64 _ulog_channels = ULOG_KMSG;
66 _ulog_channels = ULOG_STDIO;
68 _ulog_channels = ULOG_SYSLOG;
71 if (_ulog_facility < 0) {
72 if (env && !strcmp(env, "1"))
73 _ulog_facility = LOG_DAEMON;
75 _ulog_facility = LOG_USER;
77 _ulog_facility = LOG_DAEMON;
80 if (_ulog_ident == NULL && _ulog_channels != ULOG_STDIO)
81 _ulog_ident = ulog_default_ident();
83 if (_ulog_channels & ULOG_SYSLOG)
84 openlog(_ulog_ident, 0, _ulog_facility);
86 _ulog_initialized = 1;
89 static void ulog_kmsg(int priority, const char *fmt, va_list ap)
93 if ((kmsg = fopen("/dev/kmsg", "w")) != NULL) {
94 fprintf(kmsg, "<%u>", priority);
97 fprintf(kmsg, "%s: ", _ulog_ident);
99 vfprintf(kmsg, fmt, ap);
104 static void ulog_stdio(int priority, const char *fmt, va_list ap)
108 if (priority == LOG_INFO || priority == LOG_NOTICE)
112 fprintf(out, "%s: ", _ulog_ident);
114 vfprintf(out, fmt, ap);
117 static void ulog_syslog(int priority, const char *fmt, va_list ap)
119 vsyslog(priority, fmt, ap);
122 void ulog_open(int channels, int facility, const char *ident)
126 _ulog_channels = channels;
127 _ulog_facility = facility;
131 void ulog_close(void)
133 if (!_ulog_initialized)
136 if (_ulog_channels & ULOG_SYSLOG)
139 _ulog_initialized = 0;
142 void ulog_threshold(int threshold)
144 _ulog_threshold = threshold;
147 void ulog(int priority, const char *fmt, ...)
151 if (priority > _ulog_threshold)
156 if (_ulog_channels & ULOG_KMSG)
159 ulog_kmsg(priority, fmt, ap);
163 if (_ulog_channels & ULOG_STDIO)
166 ulog_stdio(priority, fmt, ap);
170 if (_ulog_channels & ULOG_SYSLOG)
173 ulog_syslog(priority, fmt, ap);