14 // Yes, it's a bit ugly.
15 #define SYSLOG_FAKE_FILE (static_cast<FILE *>(NULL))
17 bool logging_started = false;
18 std::vector<FILE *> log_destinations;
20 void add_log_destination_file(const std::string &filename)
22 FILE *fp = fopen(filename.c_str(), "a");
24 perror(filename.c_str());
28 log_destinations.push_back(fp);
31 void add_log_destination_console()
33 log_destinations.push_back(stderr);
36 void add_log_destination_syslog()
38 openlog("cubemap", LOG_PID, LOG_DAEMON);
39 log_destinations.push_back(SYSLOG_FAKE_FILE);
44 logging_started = true;
47 void shut_down_logging()
49 for (size_t i = 0; i < log_destinations.size(); ++i) {
50 if (log_destinations[i] == SYSLOG_FAKE_FILE) {
52 } else if (log_destinations[i] != stderr) {
53 if (fclose(log_destinations[i]) != 0) {
58 log_destinations.clear();
59 logging_started = false;
62 void log(LogLevel log_level, const char *fmt, ...)
64 char formatted_msg[4096];
67 vsnprintf(formatted_msg, sizeof(formatted_msg), fmt, ap);
70 const char *log_level_str;
76 syslog_level = LOG_INFO;
79 log_level_str = "INFO: ";
80 syslog_level = LOG_INFO;
83 log_level_str = "WARNING: ";
84 syslog_level = LOG_WARNING;
87 log_level_str = "ERROR: ";
88 syslog_level = LOG_ERR;
94 // Log to stderr if logging hasn't been set up yet. Note that this means
95 // that such messages will come even if there are no “error_log” lines.
96 if (!logging_started) {
97 fprintf(stderr, "%s%s\n", log_level_str, formatted_msg);
101 for (size_t i = 0; i < log_destinations.size(); ++i) {
102 if (log_destinations[i] == SYSLOG_FAKE_FILE) {
103 syslog(syslog_level, "%s", formatted_msg);
105 int err = fprintf(log_destinations[i], "%s%s\n", log_level_str, formatted_msg);
109 if (log_destinations[i] != stderr) {
110 fflush(log_destinations[i]);
116 void log_perror(const char *msg)
119 log(ERROR, "%s: %s", msg, strerror_r(errno, errbuf, sizeof(errbuf)));