add support for logging to syslog (fixes #293), log exit on errors during daemonization, log config path on error, better variable names

This commit is contained in:
john30
2019-10-06 14:12:52 +02:00
parent 0c46fb57ff
commit fa977f45f4
3 changed files with 59 additions and 31 deletions
Regular → Executable
+9 -9
View File
@@ -223,7 +223,7 @@ static const struct argp_option argpoptions[] = {
{"updatecheck", O_UPDCHK, "MODE", 0, "Set automatic update check to MODE (on|off) [on]", 0 }, {"updatecheck", O_UPDCHK, "MODE", 0, "Set automatic update check to MODE (on|off) [on]", 0 },
{nullptr, 0, nullptr, 0, "Log options:", 5 }, {nullptr, 0, nullptr, 0, "Log options:", 5 },
{"logfile", 'l', "FILE", 0, "Write log to FILE (only for daemon) [" PACKAGE_LOGFILE "]", 0 }, {"logfile", 'l', "FILE", 0, "Write log to FILE (only for daemon, empty string for using syslog) [" PACKAGE_LOGFILE "]", 0 },
{"log", O_LOG, "AREAS LEVEL", 0, "Only write log for matching AREA(S) below or equal to LEVEL" {"log", O_LOG, "AREAS LEVEL", 0, "Only write log for matching AREA(S) below or equal to LEVEL"
" (alternative to --logareas/--logevel, may be used multiple times) [all notice]", 0 }, " (alternative to --logareas/--logevel, may be used multiple times) [all notice]", 0 },
{"logareas", O_LOGARE, "AREAS", 0, "Only write log for matching AREA(S): main|network|bus|update|all" {"logareas", O_LOGARE, "AREAS", 0, "Only write log for matching AREA(S): main|network|bus|update|all"
@@ -487,7 +487,7 @@ error_t parse_opt(int key, char *arg, struct argp_state *state) {
// Log options: // Log options:
case 'l': // --logfile=/var/log/ebusd.log case 'l': // --logfile=/var/log/ebusd.log
if (arg == nullptr || arg[0] == 0 || strcmp("/", arg) == 0) { if (arg == nullptr || strcmp("/", arg) == 0) {
argp_error(state, "invalid logfile"); argp_error(state, "invalid logfile");
return EINVAL; return EINVAL;
} }
@@ -599,7 +599,7 @@ void daemonize() {
pid_t pid = fork(); pid_t pid = fork();
if (pid < 0) { if (pid < 0) {
logError(lf_main, "fork() failed"); logError(lf_main, "fork() failed, exiting");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@@ -612,14 +612,14 @@ void daemonize() {
// Create a new SID for the child process and // Create a new SID for the child process and
// detach the process from the parent (normally a shell) // detach the process from the parent (normally a shell)
if (setsid() < 0) { if (setsid() < 0) {
logError(lf_main, "setsid() failed"); logError(lf_main, "setsid() failed, exiting");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Change the current working directory. This prevents the current // Change the current working directory. This prevents the current
// directory from being locked; hence not being able to remove it. // directory from being locked; hence not being able to remove it.
if (chdir("/tmp") < 0) { if (chdir("/tmp") < 0) {
logError(lf_main, "daemon chdir() failed"); logError(lf_main, "daemon chdir() failed, exiting");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@@ -642,7 +642,7 @@ void daemonize() {
} }
} }
if (pidFile == nullptr) { if (pidFile == nullptr) {
logError(lf_main, "can't open pidfile: %s", opt.pidFile); logError(lf_main, "can't open pidfile: %s, exiting", opt.pidFile);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@@ -701,7 +701,7 @@ void signalHandler(int sig) {
switch (sig) { switch (sig) {
case SIGHUP: case SIGHUP:
logNotice(lf_main, "SIGHUP received"); logNotice(lf_main, "SIGHUP received");
if (!opt.foreground) { if (!opt.foreground && opt.logFile && opt.logFile[0] != 0) { // for log file rotation
closeLogFile(); closeLogFile();
setLogFile(opt.logFile); setLogFile(opt.logFile);
} }
@@ -988,8 +988,8 @@ result_t loadConfigFiles(MessageMap* messages, bool verbose, bool denyRecursive)
if (result == RESULT_OK) { if (result == RESULT_OK) {
logInfo(lf_main, "read config files"); logInfo(lf_main, "read config files");
} else { } else {
logError(lf_main, "error reading config files: %s, last error: %s", getResultCode(result), logError(lf_main, "error reading config files from %s: %s, last error: %s", opt.configPath,
errorDescription.c_str()); getResultCode(result), errorDescription.c_str());
} }
messages->unlock(); messages->unlock();
return RESULT_OK; return RESULT_OK;
+49 -21
View File
@@ -27,12 +27,13 @@
#include <sys/time.h> #include <sys/time.h>
#include <stdarg.h> #include <stdarg.h>
#include <string.h> #include <string.h>
#include <syslog.h>
#include "lib/utils/clock.h" #include "lib/utils/clock.h"
namespace ebusd { namespace ebusd {
/** the name of each @a LogFacility. */ /** the name of each @a LogFacility. */
static const char *facilityNames[] = { static const char *s_facilityNames[] = {
"main", "main",
"network", "network",
"bus", "bus",
@@ -43,7 +44,7 @@ static const char *facilityNames[] = {
}; };
/** the name of each @a LogLevel. */ /** the name of each @a LogLevel. */
static const char* levelNames[] = { static const char* s_levelNames[] = {
"none", "none",
"error", "error",
"notice", "notice",
@@ -52,19 +53,32 @@ static const char* levelNames[] = {
nullptr nullptr
}; };
/** the syslog level of each @a LogLevel. */
static const int s_syslogLevels[] = {
LOG_INFO,
LOG_ERR,
LOG_NOTICE,
LOG_INFO,
LOG_DEBUG,
0
};
/** the current log level by log facility. */ /** the current log level by log facility. */
static LogLevel s_facilityLogLevel[] = { ll_notice, ll_notice, ll_notice, ll_notice, ll_notice, }; static LogLevel s_facilityLogLevel[] = { ll_notice, ll_notice, ll_notice, ll_notice, ll_notice, };
/** the current log FILE. */ /** the current log FILE, or nullptr if closed or syslog is used. */
static FILE* s_logFile = stdout; static FILE* s_logFile = stdout;
/** whether to log to syslog. */
static bool s_useSyslog = false;
LogFacility parseLogFacility(const char* facility) { LogFacility parseLogFacility(const char* facility) {
if (!facility) { if (!facility) {
return lf_COUNT; return lf_COUNT;
} }
char *input = strdup(facility); char *input = strdup(facility);
char *opt = reinterpret_cast<char*>(input), *value = nullptr; char *opt = reinterpret_cast<char*>(input), *value = nullptr;
int val = getsubopt(&opt, (char *const *)facilityNames, &value); int val = getsubopt(&opt, (char *const *)s_facilityNames, &value);
if (val < 0 || val >= lf_COUNT || value || *opt) { if (val < 0 || val >= lf_COUNT || value || *opt) {
free(input); free(input);
return lf_COUNT; return lf_COUNT;
@@ -78,7 +92,7 @@ int parseLogFacilities(const char* facilities) {
char *opt = reinterpret_cast<char*>(input), *value = nullptr; char *opt = reinterpret_cast<char*>(input), *value = nullptr;
int newFacilites = 0; int newFacilites = 0;
while (*opt) { while (*opt) {
int val = getsubopt(&opt, (char *const *)facilityNames, &value); int val = getsubopt(&opt, (char *const *)s_facilityNames, &value);
if (val < 0 || val > lf_COUNT || value) { if (val < 0 || val > lf_COUNT || value) {
free(input); free(input);
return -1; return -1;
@@ -99,7 +113,7 @@ LogLevel parseLogLevel(const char* level) {
} }
char *input = strdup(level); char *input = strdup(level);
char *opt = reinterpret_cast<char*>(input), *value = nullptr; char *opt = reinterpret_cast<char*>(input), *value = nullptr;
int val = getsubopt(&opt, (char *const *)levelNames, &value); int val = getsubopt(&opt, (char *const *)s_levelNames, &value);
if (val < 0 || val >= ll_COUNT || value || *opt) { if (val < 0 || val >= ll_COUNT || value || *opt) {
free(input); free(input);
return ll_COUNT; return ll_COUNT;
@@ -109,11 +123,11 @@ LogLevel parseLogLevel(const char* level) {
} }
const char* getLogFacilityStr(LogFacility facility) { const char* getLogFacilityStr(LogFacility facility) {
return facilityNames[facility]; return s_facilityNames[facility];
} }
const char* getLogLevelStr(LogLevel level) { const char* getLogLevelStr(LogLevel level) {
return levelNames[level]; return s_levelNames[level];
} }
bool setFacilitiesLogLevel(int facilities, LogLevel level) { bool setFacilitiesLogLevel(int facilities, LogLevel level) {
@@ -132,6 +146,12 @@ LogLevel getFacilityLogLevel(LogFacility facility) {
} }
bool setLogFile(const char* filename) { bool setLogFile(const char* filename) {
if (filename[0] == 0) {
closeLogFile();
openlog("ebusd", LOG_NDELAY|LOG_PID, LOG_USER);
s_useSyslog = true;
return true;
}
FILE* newFile = fopen(filename, "a"); FILE* newFile = fopen(filename, "a");
if (newFile == nullptr) { if (newFile == nullptr) {
return false; return false;
@@ -148,27 +168,35 @@ void closeLogFile() {
} }
s_logFile = nullptr; s_logFile = nullptr;
} }
if (s_useSyslog) {
closelog();
s_useSyslog = false;
}
} }
bool needsLog(const LogFacility facility, const LogLevel level) { bool needsLog(const LogFacility facility, const LogLevel level) {
return s_facilityLogLevel[facility] >= level; return s_facilityLogLevel[facility] >= level;
} }
void logWrite(const char* facility, const char* level, const char* message, va_list ap) { void logWrite(const char* facility, const LogLevel level, const char* message, va_list ap) {
if (s_logFile == nullptr) { if (s_logFile == nullptr && !s_useSyslog) {
return; return;
} }
struct timespec ts;
struct tm td;
clockGettime(&ts);
localtime_r(&ts.tv_sec, &td);
char* buf; char* buf;
if (vasprintf(&buf, message, ap) >= 0 && buf) { if (vasprintf(&buf, message, ap) >= 0 && buf) {
fprintf(s_logFile, "%04d-%02d-%02d %02d:%02d:%02d.%03ld [%s %s] %s\n", if (s_useSyslog) {
td.tm_year+1900, td.tm_mon+1, td.tm_mday, syslog(s_syslogLevels[level], "[%s %s] %s", facility, s_levelNames[level], buf);
td.tm_hour, td.tm_min, td.tm_sec, ts.tv_nsec/1000000, } else {
facility, level, buf); struct timespec ts;
fflush(s_logFile); struct tm td;
clockGettime(&ts);
localtime_r(&ts.tv_sec, &td);
fprintf(s_logFile, "%04d-%02d-%02d %02d:%02d:%02d.%03ld [%s %s] %s\n",
td.tm_year+1900, td.tm_mon+1, td.tm_mday,
td.tm_hour, td.tm_min, td.tm_sec, ts.tv_nsec/1000000,
facility, s_levelNames[level], buf);
fflush(s_logFile);
}
} }
if (buf) { if (buf) {
free(buf); free(buf);
@@ -178,14 +206,14 @@ void logWrite(const char* facility, const char* level, const char* message, va_l
void logWrite(const LogFacility facility, const LogLevel level, const char* message, ...) { void logWrite(const LogFacility facility, const LogLevel level, const char* message, ...) {
va_list ap; va_list ap;
va_start(ap, message); va_start(ap, message);
logWrite(facilityNames[facility], levelNames[level], message, ap); logWrite(s_facilityNames[facility], level, message, ap);
va_end(ap); va_end(ap);
} }
void logWrite(const char* facility, const LogLevel level, const char* message, ...) { void logWrite(const char* facility, const LogLevel level, const char* message, ...) {
va_list ap; va_list ap;
va_start(ap, message); va_start(ap, message);
logWrite(facility, levelNames[level], message, ap); logWrite(facility, level, message, ap);
va_end(ap); va_end(ap);
} }
+1 -1
View File
@@ -98,7 +98,7 @@ LogLevel getFacilityLogLevel(LogFacility facility);
/** /**
* Set the log file to use. * Set the log file to use.
* @param filename the name of the log file to use. * @param filename the name of the log file to use, or the empty string for syslog.
* @return true on success, false on error. * @return true on success, false on error.
*/ */
bool setLogFile(const char* filename); bool setLogFile(const char* filename);