2023-01-05 10:27:14 +00:00
|
|
|
#include <ctime>
|
|
|
|
#include <string>
|
|
|
|
#include <vector>
|
|
|
|
|
|
|
|
#include "log.h"
|
|
|
|
|
2023-01-29 08:21:22 +00:00
|
|
|
std::vector<LogEntry> log_entries;
|
2023-01-05 10:27:14 +00:00
|
|
|
|
2023-01-29 08:21:22 +00:00
|
|
|
LogEntry::LogEntry(time_t time_, std::string message_) : time(time_), message(std::move(message_)) {
|
|
|
|
size_t pos;
|
2023-01-05 10:27:14 +00:00
|
|
|
|
2023-01-29 08:21:22 +00:00
|
|
|
while ((pos = this->message.find('\n')) != std::string::npos) {
|
|
|
|
this->message.replace(pos, 1, 1, ' ');
|
2023-01-16 03:57:07 +00:00
|
|
|
}
|
2023-01-29 08:21:22 +00:00
|
|
|
}
|
2023-01-05 10:27:14 +00:00
|
|
|
|
2023-01-29 08:21:22 +00:00
|
|
|
|
2023-02-09 07:44:34 +00:00
|
|
|
std::string to_string(const LogEntry& entry) {
|
2023-02-03 04:59:51 +00:00
|
|
|
struct tm tm;
|
2023-01-29 08:21:22 +00:00
|
|
|
char time_as_str[128] = {0};
|
2023-02-03 04:59:51 +00:00
|
|
|
strftime(time_as_str, 127 * sizeof(char), "%c", localtime_r(&entry.time, &tm));
|
2023-01-29 08:21:22 +00:00
|
|
|
return std::string(1, '[') + time_as_str + "] " + entry.message;
|
2023-01-16 08:56:07 +00:00
|
|
|
}
|
|
|
|
|
2023-01-29 08:21:22 +00:00
|
|
|
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());
|
2023-01-16 08:56:07 +00:00
|
|
|
}
|
|
|
|
|
2023-01-29 08:21:22 +00:00
|
|
|
void log(LogEntry entry, bool print) {
|
2023-01-20 15:22:21 +00:00
|
|
|
if (print) {
|
2023-01-29 08:21:22 +00:00
|
|
|
print_log(entry);
|
2023-01-16 03:57:07 +00:00
|
|
|
}
|
2023-01-29 08:21:22 +00:00
|
|
|
log_entries.push_back(std::move(entry));
|
2023-01-05 10:27:14 +00:00
|
|
|
}
|
|
|
|
|
2023-01-29 08:21:22 +00:00
|
|
|
void log(std::string message) {
|
|
|
|
log({time(nullptr), std::move(message)});
|
2023-01-07 09:15:21 +00:00
|
|
|
}
|