Adds 2017 to copyrights
[src/app-framework-main.git] / src / verbose.c
1 /*
2  Copyright (C) 2016, 2017 "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         openlog(name, LOG_PERROR, authority ? LOG_AUTH : LOG_USER);
47 }
48
49 #else
50
51 #include <unistd.h>
52
53 static const char *appname;
54
55 static int appauthority;
56
57 static const char *prefixes[] = {
58         "<0> EMERGENCY",
59         "<1> ALERT",
60         "<2> CRITICAL",
61         "<3> ERROR",
62         "<4> WARNING",
63         "<5> NOTICE",
64         "<6> INFO",
65         "<7> DEBUG"
66 };
67
68 void vverbose(int level, const char *file, int line, const char *fmt, va_list args)
69 {
70         int tty = isatty(fileno(stderr));
71
72         fprintf(stderr, "%s: ", prefixes[LEVEL(level)] + (tty ? 4 : 0));
73         vfprintf(stderr, fmt, args);
74         if (file != NULL && (!tty || verbosity >5))
75                 fprintf(stderr, " [%s:%d]\n", file, line);
76         else
77                 fprintf(stderr, "\n");
78 }
79
80 void verbose_set_name(const char *name, int authority)
81 {
82         appname = name;
83         appauthority = authority;
84 }
85
86 #endif
87
88 void verbose(int level, const char *file, int line, const char *fmt, ...)
89 {
90         va_list ap;
91
92         va_start(ap, fmt);
93         vverbose(level, file, line, fmt, ap);
94         va_end(ap);
95 }
96