2 * Copyright (C) 2007 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
23 static char *debug_ident = NULL;
24 static uint8_t debug_level = DBG_INFO;
25 static FILE *debug_file = NULL;
26 static int debug_syslogfacility = 0;
27 static uint8_t debug_timestamp = 0;
29 void debug_init(char *ident) {
31 setvbuf(debug_file, NULL, _IONBF, 0);
35 void debug_set_level(uint8_t level) {
38 debug_level = DBG_ERR;
41 debug_level = DBG_WARN;
44 debug_level = DBG_INFO;
47 debug_level = DBG_DBG;
52 void debug_timestamp_on() {
56 uint8_t debug_get_level() {
60 int debug_set_destination(char *dest) {
61 static const char *facstrings[] = { "LOG_DAEMON", "LOG_MAIL", "LOG_USER", "LOG_LOCAL0",
62 "LOG_LOCAL1", "LOG_LOCAL2", "LOG_LOCAL3", "LOG_LOCAL4",
63 "LOG_LOCAL5", "LOG_LOCAL6", "LOG_LOCAL7", NULL };
64 static const int facvals[] = { LOG_DAEMON, LOG_MAIL, LOG_USER, LOG_LOCAL0,
65 LOG_LOCAL1, LOG_LOCAL2, LOG_LOCAL3, LOG_LOCAL4,
66 LOG_LOCAL5, LOG_LOCAL6, LOG_LOCAL7 };
70 if (!strncasecmp(dest, "file:///", 8)) {
71 debug_file = fopen(dest + 7, "a");
74 debugx(1, DBG_ERR, "Failed to open logfile %s\n%s",
75 dest + 7, strerror(errno));
77 setvbuf(debug_file, NULL, _IONBF, 0);
80 if (!strncasecmp(dest, "x-syslog://", 11)) {
85 for (i = 0; facstrings[i]; i++)
86 if (!strcasecmp(dest, facstrings[i]))
89 debugx(1, DBG_ERR, "Unknown syslog facility %s", dest);
90 debug_syslogfacility = facvals[i];
92 debug_syslogfacility = LOG_DAEMON;
93 openlog(debug_ident, LOG_PID, debug_syslogfacility);
96 debug(DBG_ERR, "Unknown log destination, exiting %s", dest);
100 void debug_logit(uint8_t level, const char *format, va_list ap) {
105 if (debug_syslogfacility) {
108 priority = LOG_DEBUG;
114 priority = LOG_WARNING;
120 priority = LOG_DEBUG;
122 vsyslog(priority, format, ap);
124 if (debug_timestamp && (timebuf = malloc(256))) {
125 gettimeofday(&now, NULL);
126 ctime_r(&now.tv_sec, timebuf);
127 timebuf[strlen(timebuf) - 1] = '\0';
128 fprintf(debug_file, "%s: ", timebuf + 4);
131 vfprintf(debug_file, format, ap);
132 fprintf(debug_file, "\n");
136 void debug(uint8_t level, char *format, ...) {
138 if (level < debug_level)
140 va_start(ap, format);
141 debug_logit(level, format, ap);
145 void debugx(int status, uint8_t level, char *format, ...) {
146 if (level >= debug_level) {
148 va_start(ap, format);
149 debug_logit(level, format, ap);