41 lines
1.0 KiB
C++
41 lines
1.0 KiB
C++
#include <ctime>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
#include "log.h"
|
|
|
|
std::vector<LogEntry> log_entries;
|
|
|
|
LogEntry::LogEntry(time_t time_, std::string message_) : time(time_), message(std::move(message_)) {
|
|
size_t pos;
|
|
|
|
while ((pos = this->message.find('\n')) != std::string::npos) {
|
|
this->message.replace(pos, 1, 1, ' ');
|
|
}
|
|
}
|
|
|
|
|
|
std::string to_string(const LogEntry& entry) {
|
|
struct tm tm;
|
|
char time_as_str[128] = {0};
|
|
strftime(time_as_str, 127 * sizeof(char), "%c", localtime_r(&entry.time, &tm));
|
|
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", localtime(&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)});
|
|
}
|