logmeow/log.cpp

72 lines
1.7 KiB
C++
Raw Normal View History

2023-01-05 10:27:14 +00:00
#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);
}
2023-01-07 09:15:21 +00:00
void log(std::string entry) {
log(std::move(entry), current_time());
}
void log(std::string action, const std::exception& e, time_t time) {
log(action + ": " + e.what(), time);
}
2023-01-05 10:27:14 +00:00
void log(std::string action, const std::exception& e) {
2023-01-07 09:15:21 +00:00
log(std::move(action), e, current_time());
2023-01-05 10:27:14 +00:00
}
std::string quote(const std::string& str) {
std::stringstream ss;
ss << std::quoted(str);
return ss.str();
}