logmeow/log.cpp

41 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-03-30 14:24:01 +00:00
LogEntry::LogEntry(time_t time, std::string message_) : message(std::move(message_)) {
2023-01-29 08:21:22 +00:00
size_t pos;
2023-01-05 10:27:14 +00:00
2023-03-30 14:24:01 +00:00
localtime_r(&time, &this->time);
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
2023-02-09 07:44:34 +00:00
std::string to_string(const LogEntry& entry) {
2023-01-29 08:21:22 +00:00
char time_as_str[128] = {0};
2023-03-30 14:24:01 +00:00
strftime(time_as_str, 127 * sizeof(char), "%c", &entry.time);
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};
2023-03-30 14:24:01 +00:00
strftime(time_as_str, 127 * sizeof(char), "%c", &entry.time);
2023-01-29 08:21:22 +00:00
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
}