tools/thermal: Add util library
[linux-2.6-microblaze.git] / tools / thermal / lib / log.c
1 // SPDX-License-Identifier: LGPL-2.1+
2 // Copyright (C) 2022, Linaro Ltd - Daniel Lezcano <daniel.lezcano@linaro.org>
3 #include <stdarg.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <syslog.h>
7 #include "log.h"
8
9 static const char *__ident = "unknown";
10 static int __options;
11
12 static const char * const loglvl[] = {
13         [LOG_DEBUG]     = "DEBUG",
14         [LOG_INFO]      = "INFO",
15         [LOG_NOTICE]    = "NOTICE",
16         [LOG_WARNING]   = "WARN",
17         [LOG_ERR]       = "ERROR",
18         [LOG_CRIT]      = "CRITICAL",
19         [LOG_ALERT]     = "ALERT",
20         [LOG_EMERG]     = "EMERG",
21 };
22
23 int log_str2level(const char *lvl)
24 {
25         int i;
26
27         for (i = 0; i < sizeof(loglvl) / sizeof(loglvl[LOG_DEBUG]); i++)
28                 if (!strcmp(lvl, loglvl[i]))
29                         return i;
30
31         return LOG_DEBUG;
32 }
33
34 extern void logit(int level, const char *format, ...)
35 {
36         va_list args;
37
38         va_start(args, format);
39
40         if (__options & TO_SYSLOG)
41                 vsyslog(level, format, args);
42
43         if (__options & TO_STDERR)
44                 vfprintf(stderr, format, args);
45
46         if (__options & TO_STDOUT)
47                 vfprintf(stdout, format, args);
48
49         va_end(args);
50 }
51
52 int log_init(int level, const char *ident, int options)
53 {
54         if (!options)
55                 return -1;
56
57         if (level > LOG_DEBUG)
58                 return -1;
59
60         if (!ident)
61                 return -1;
62
63         __ident = ident;
64         __options = options;
65
66         if (options & TO_SYSLOG) {
67                 openlog(__ident, options | LOG_NDELAY, LOG_USER);
68                 setlogmask(LOG_UPTO(level));
69         }
70
71         return 0;
72 }
73
74 void log_exit(void)
75 {
76         closelog();
77 }