#include "logger.h" #include "options.h" /// Logger that writes to a file class FileLogDriver : public LogDriverBase { public: FileLogDriver() : file(fopen(path.c_str(), openmode.c_str())) { } ~FileLogDriver() { fclose(file); } void message(int priority, const char * msg) const { if (priority <= level) { struct tm tm; time_t t = time(NULL); localtime_r(&t, &tm); char tmbuf[30]; strftime(tmbuf, sizeof(tmbuf), "%F %T", &tm); fprintf(file, "%s %-6.*s%s\n", tmbuf, 5, Log::priorityName(level), msg); fflush(file); } } INITOPTIONS; static int level; private: static std::string path; static std::string openmode; FILE * file; }; DECLARE_OPTIONS(FileLogDriver, "File log options") ("common.filelog.level", Options::value(&level, -1), "Log to file with level (default OFF)") ("common.filelog.path", Options::value(&path, "/var/log/project2.log"), "Log to file with path (default '/var/log/project2.log')") ("common.filelog.openmode", Options::value(&openmode, "a"), "How to open the log file (see man 3 fopen) (default 'a')") END_OPTIONS(FileLogDriver); int FileLogDriver::level; std::string FileLogDriver::path; std::string FileLogDriver::openmode; DECLARE_LOGGER_LOADER("file", FileLogDriver);