mason/src/loggger.cpp

76 lines
2.1 KiB
C++

#include "loggger.h"
constexpr const std::array<std::string_view, static_cast<int>(Logger::Severity::fatal) + 1> logSettings({
/*debug*/ "\e[90m",
/*info*/ "\e[32m",
/*minor*/ "\e[34m",
/*major*/ "\e[94m",
/*warning*/ "\e[33m",
/*error*/ "\e[31m",
/*fatal*/ "\e[91m"
});
constexpr const std::array<std::string_view, static_cast<int>(Logger::Severity::fatal) + 1> logHeaders({
/*debug*/ "DEBUG: ",
/*info*/ "INFO: ",
/*minor*/ "MINOR: ",
/*major*/ "MAJOR: ",
/*warning*/ "WARNING: ",
/*error*/ "ERROR: ",
/*fatal*/ "FATAL: "
});
constexpr const std::string_view bold("\e[1m");
constexpr const std::string_view regular("\e[22m");
constexpr const std::string_view clearStyle("\e[0m");
Logger::Logger(Logger::Severity severity, bool accumulate):
accumulate(accumulate),
currentSeverity(severity),
history(),
readMutex(),
writeMutex()
{}
Logger::~Logger()
{}
void Logger::printLog(bool colored) const {
std::cout << std::endl;
std::scoped_lock lock(readMutex);
for (const Message& message : history)
printMessage(message, colored);
if (colored)
std::cout << clearStyle << std::flush;
}
void Logger::log(Logger::Severity severity, const std::string& comment, bool colored) const {
if (severity < currentSeverity)
return;
if (accumulate) {
std::scoped_lock lock(readMutex, writeMutex);
history.emplace_back(severity, comment);
} else {
std::scoped_lock lock(writeMutex);
printMessage({severity, comment}, colored);
if (colored)
std::cout << clearStyle << std::flush;
}
}
std::list<std::pair<Logger::Severity, std::string>> Logger::getLog() const {
std::scoped_lock lock(readMutex);
return history;
}
void Logger::printMessage(const Message& message, bool colored) const {
if (colored) {
int severity = static_cast<int>(message.first);
std::cout << logSettings[severity] << bold << logHeaders[severity] << regular;
}
std::cout << message.second << std::endl;
}