50582368e497d0ad3f69a4f216823f1501c3d8b8
[src/app-framework-main.git] / src / verbose.c
1 /*
2  Copyright (C) 2016, 2017, 2018 "IoT.bzh"
3
4  author: José Bollo <jose.bollo@iot.bzh>
5
6  Licensed under the Apache License, Version 2.0 (the "License");
7  you may not use this file except in compliance with the License.
8  You may obtain a copy of the License at
9
10      http://www.apache.org/licenses/LICENSE-2.0
11
12  Unless required by applicable law or agreed to in writing, software
13  distributed under the License is distributed on an "AS IS" BASIS,
14  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  See the License for the specific language governing permissions and
16  limitations under the License.
17 */
18
19 #include <stdio.h>
20 #include <stdarg.h>
21
22 #include "verbose.h"
23
24 int verbosity = 1;
25
26 #define LEVEL(x) ((x) < 0 ? 0 : (x) > 7 ? 7 : (x))
27
28 #if defined(VERBOSE_WITH_SYSLOG)
29
30 #include <syslog.h>
31
32 void vverbose(int level, const char *file, int line, const char *fmt, va_list args)
33 {
34         char *p;
35
36         if (file == NULL || vasprintf(&p, fmt, args) < 0)
37                 vsyslog(level, fmt, args);
38         else {
39                 syslog(LEVEL(level), "%s [%s:%d]", p, file, line);
40                 free(p);
41         }
42 }
43
44 void verbose_set_name(const char *name, int authority)
45 {
46         closelog();
47         openlog(name, LOG_PERROR, authority ? LOG_AUTH : LOG_USER);
48 }
49
50 #else
51
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55 #include <errno.h>
56
57 static char *appname;
58
59 static int appauthority;
60
61 static const char *prefixes[] = {
62         "<0> EMERGENCY",
63         "<1> ALERT",
64         "<2> CRITICAL",
65         "<3> ERROR",
66         "<4> WARNING",
67         "<5> NOTICE",
68         "<6> INFO",
69         "<7> DEBUG"
70 };
71
72 void vverbose(int level, const char *file, int line, const char *fmt, va_list args)
73 {
74         int saverr = errno;
75         int tty = isatty(fileno(stderr));
76         errno = saverr;
77
78         fprintf(stderr, "%s: ", prefixes[LEVEL(level)] + (tty ? 4 : 0));
79         vfprintf(stderr, fmt, args);
80         if (file != NULL && (!tty || verbosity >5))
81                 fprintf(stderr, " [%s:%d]\n", file, line);
82         else
83                 fprintf(stderr, "\n");
84 }
85
86 void verbose_set_name(const char *name, int authority)
87 {
88         free(appname);
89         appname = name ? strdup(name) : NULL;
90         appauthority = authority;
91 }
92
93 #endif
94
95 void verbose(int level, const char *file, int line, const char *fmt, ...)
96 {
97         va_list ap;
98
99         va_start(ap, fmt);
100         vverbose(level, file, line, fmt, ap);
101         va_end(ap);
102 }
103