summaryrefslogtreecommitdiffstats
path: root/src/reporting.c
blob: 4be6e1b8f25be7aeb6fec280327e48ffc20d8985 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
#include <sys/types.h>
#include <syslog.h>

#include "reporting.h"

int verbosity_level = REPORT_WARNING;
static int syslog_flag = 0;
/* for converting our own levels to syslog's levels: */
static int log_levels[5] = { LOG_ALERT, LOG_ERR, LOG_WARNING, LOG_INFO, LOG_DEBUG };

void reporting_init(const char *program_name)
{
	openlog(program_name, LOG_PID, LOG_USER);
	/* reporting to syslog is on by default if stderr is not printed at a terminal */
	if (!isatty(fileno(stderr)))
		reporting_use_syslog(1);
}

void reporting_use_syslog(int flag)
{
	syslog_flag = flag;
}

void reporting_verbosity(int level)
{
	verbosity_level = level;
}

void report_message(int level, const char *format, ...)
{
	va_list args;
	va_start(args, format);

	if(syslog_flag || level == REPORT_ALERT) {
		vsyslog(LOG_USER | log_levels[level], format, args);
		/* va_list can only be used once */
		va_end(args);
		va_start(args, format);
	}

	vfprintf(stderr, format, args);
	va_end(args);
}

/* For messages which contain sensitive information, and should not be shown to
 * all users: */
void report_private_message(int level, const char *format, ...)
{
	if(level <= verbosity_level)
	{
		va_list args;
		va_start(args, format);

		if(syslog_flag || level == REPORT_ALERT) {
			syslog(LOG_AUTHPRIV | log_levels[level], format, args);
			/* va_list can only be used once */
			va_end(args);
			va_start(args, format);
		}

		if (getuid() == 0) /* being run by root */
			vfprintf(stderr, format, args);

		va_end(args);
	}
}