logmeow/log.cpp

40 lines
1020 B
C++
Raw Normal View History

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-29 08:21:22 +00:00
}
2023-01-05 10:27:14 +00:00
2023-01-29 08:21:22 +00:00
std::string format_log(const LogEntry& entry) {
char time_as_str[128] = {0};
strftime(time_as_str, 127 * sizeof(char), "%c", localtime(&entry.time));
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-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
}