logmeow/log.cpp

41 lines
1020 B
C++

#include <ctime>
#include <string>
#include <vector>
#include "log.h"
std::vector<LogEntry> log_entries;
LogEntry::LogEntry(time_t time, std::string message_) : message(std::move(message_)) {
size_t pos;
localtime_r(&time, &this->time);
while ((pos = this->message.find('\n')) != std::string::npos) {
this->message.replace(pos, 1, 1, ' ');
}
}
std::string to_string(const LogEntry& entry) {
char time_as_str[128] = {0};
strftime(time_as_str, 127 * sizeof(char), "%c", &entry.time);
return std::string(1, '[') + time_as_str + "] " + entry.message;
}
void print_log(const LogEntry& entry) {
char time_as_str[128] = {0};
strftime(time_as_str, 127 * sizeof(char), "%c", &entry.time);
fprintf(stderr, "[%s] %s\n", time_as_str, entry.message.c_str());
}
void log(LogEntry entry, bool print) {
if (print) {
print_log(entry);
}
log_entries.push_back(std::move(entry));
}
void log(std::string message) {
log({time(nullptr), std::move(message)});
}