logmeow/log.cpp

64 lines
1.5 KiB
C++

#include <ctime>
#include <string>
#include <vector>
#include <iomanip>
#include <sstream>
#include <iostream>
#include <exception>
#include <system_error>
#include "log.h"
static time_t current_time() {
static bool no_time_warned = false;
struct timespec tp;
if (!clock_gettime(CLOCK_REALTIME, &tp)) {
return tp.tv_sec;
}
if (no_time_warned) {
return 0;
}
no_time_warned = true;
std::system_error e = std::system_error(errno, std::generic_category(), "clock_gettime()");
log("Failed to get current time", std::move(e));
return 0;
}
std::string log_entries;
void log(std::string entry, time_t time) {
size_t last_newline_pos = 0, newline_pos;
std::string line;
char time_as_str[128] = {0};
strftime(time_as_str, 127 * sizeof(char), "%c", localtime(&time));
do {
newline_pos = entry.find('\n', last_newline_pos);
line = '[';
line += time_as_str;
line += "] ";
line += entry.substr(last_newline_pos, newline_pos);
printf("%s\n", line.c_str());
if (!log_entries.empty()) {
log_entries += '\n';
}
log_entries += std::move(line);
last_newline_pos = newline_pos + 1;
} while (last_newline_pos);
}
void log(std::string action, const std::exception& e) {
log(action + ": " + e.what(), current_time());
}
std::string quote(const std::string& str) {
std::stringstream ss;
ss << std::quoted(str);
return ss.str();
}