1/***
2  This file is part of libdaemon.
3
4  Copyright 2003-2008 Lennart Poettering
5
6  Permission is hereby granted, free of charge, to any person obtaining a copy
7  of this software and associated documentation files (the "Software"), to deal
8  in the Software without restriction, including without limitation the rights
9  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  copies of the Software, and to permit persons to whom the Software is
11  furnished to do so, subject to the following conditions:
12
13  The above copyright notice and this permission notice shall be included in
14  all copies or substantial portions of the Software.
15
16  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  SOFTWARE.
23
24***/
25
26#ifdef HAVE_CONFIG_H
27#include <config.h>
28#endif
29
30#include <stdarg.h>
31#include <stdio.h>
32#include <string.h>
33#include <errno.h>
34
35#include "dlog.h"
36
37enum daemon_log_flags daemon_log_use = DAEMON_LOG_AUTO|DAEMON_LOG_STDERR;
38const char* daemon_log_ident = NULL;
39
40static int daemon_verbosity_level = LOG_INFO;
41
42void daemon_set_verbosity(int verbosity_prio) {
43
44    /* Allow using negative verbosity levels to hide _all_ messages */
45    if (verbosity_prio > 0 && (verbosity_prio & LOG_PRIMASK) != LOG_PRIMASK)
46        daemon_log(LOG_ERR, "The value %d is not a valid priority value", verbosity_prio);
47
48    daemon_verbosity_level = verbosity_prio & LOG_PRIMASK;
49}
50
51void daemon_logv(int prio, const char* template, va_list arglist) {
52    int saved_errno;
53
54    saved_errno = errno;
55
56    if (daemon_log_use & DAEMON_LOG_SYSLOG) {
57        openlog(daemon_log_ident ? daemon_log_ident : "UNKNOWN", LOG_PID, LOG_DAEMON);
58        vsyslog(prio | LOG_DAEMON, template, arglist);
59    }
60
61    if (prio > daemon_verbosity_level)
62        goto end_daemon_logv;
63
64    if (daemon_log_use & DAEMON_LOG_STDERR) {
65        vfprintf(stderr, template, arglist);
66        fprintf(stderr, "\n");
67    }
68
69    if (daemon_log_use & DAEMON_LOG_STDOUT) {
70        vfprintf(stdout, template, arglist);
71        fprintf(stdout, "\n");
72    }
73
74 end_daemon_logv:
75    errno = saved_errno;
76}
77
78void daemon_log(int prio, const char* template, ...) {
79    va_list arglist;
80
81    va_start(arglist, template);
82    daemon_logv(prio, template, arglist);
83    va_end(arglist);
84}
85
86char *daemon_ident_from_argv0(char *argv0) {
87    char *p;
88
89    if ((p = strrchr(argv0, '/')))
90        return p+1;
91
92    return argv0;
93}
94