Set application id when forking
[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         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
56 static char *appname;
57
58 static int appauthority;
59
60 static const char *prefixes[] = {
61         "<0> EMERGENCY",
62         "<1> ALERT",
63         "<2> CRITICAL",
64         "<3> ERROR",
65         "<4> WARNING",
66         "<5> NOTICE",
67         "<6> INFO",
68         "<7> DEBUG"
69 };
70
71 void vverbose(int level, const char *file, int line, const char *fmt, va_list args)
72 {
73         int tty = isatty(fileno(stderr));
74
75         fprintf(stderr, "%s: ", prefixes[LEVEL(level)] + (tty ? 4 : 0));
76         vfprintf(stderr, fmt, args);
77         if (file != NULL && (!tty || verbosity >5))
78                 fprintf(stderr, " [%s:%d]\n", file, line);
79         else
80                 fprintf(stderr, "\n");
81 }
82
83 void verbose_set_name(const char *name, int authority)
84 {
85         free(appname);
86         appname = name ? strdup(name) : NULL;
87         appauthority = authority;
88 }
89
90 #endif
91
92 void verbose(int level, const char *file, int line, const char *fmt, ...)
93 {
94         va_list ap;
95
96         va_start(ap, fmt);
97         vverbose(level, file, line, fmt, ap);
98         va_end(ap);
99 }
100