logmeow/log.cpp

45 lines
1.1 KiB
C++

#include <ctime>
#include <string>
#include <vector>
#include <exception>
#include "log.h"
std::string log_entries;
std::vector<size_t> log_entry_line_offsets = {0};
std::string format_log(std::string entry, time_t time) {
size_t newline_pos;
char time_as_str[128] = {0};
strftime(time_as_str, 127 * sizeof(char), "%c", localtime(&time));
while ((newline_pos = entry.find('\n')) != std::string::npos) {
entry.replace(newline_pos, 1, 1, ' ');
}
return std::string(1, '[') + time_as_str + "] " + std::move(entry);
}
std::string format_log(std::string entry) {
return format_log(std::move(entry), time(nullptr));
}
void log_raw(std::string line, bool print) {
if (print) {
printf("%s\n", line.c_str());
}
if (!log_entries.empty()) {
log_entries += '\n';
log_entry_line_offsets.push_back(log_entries.size());
}
log_entries += std::move(line);
}
void log(std::string entry, time_t time) {
log_raw(format_log(std::move(entry), time));
}
void log(std::string entry) {
log_raw(format_log(std::move(entry)));
}