1
0
mirror of https://github.com/vcmi/vcmi.git synced 2024-12-14 10:12:59 +02:00
vcmi/lib/logging/CLogger.cpp

450 lines
11 KiB
C++
Raw Normal View History

/*
* CLogger.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "CLogger.h"
#ifdef VCMI_ANDROID
#include <android/log.h>
2023-02-26 11:18:24 +02:00
VCMI_LIB_NAMESPACE_BEGIN
namespace ELogLevel
{
int toAndroid(ELogLevel logLevel)
{
switch (logLevel)
{
case TRACE: return ANDROID_LOG_VERBOSE;
case DEBUG: return ANDROID_LOG_DEBUG;
case INFO: return ANDROID_LOG_INFO;
case WARN: return ANDROID_LOG_WARN;
case ERROR: return ANDROID_LOG_ERROR;
2017-07-17 23:04:00 +02:00
default:
break;
}
return ANDROID_LOG_UNKNOWN;
}
}
2023-02-26 11:18:24 +02:00
VCMI_LIB_NAMESPACE_END
2021-03-13 12:47:06 +02:00
#elif defined(VCMI_IOS)
2022-08-15 15:29:11 +02:00
#import "iOS_utils.h"
2021-03-20 16:05:32 +02:00
extern "C" {
2021-03-13 12:47:06 +02:00
#include <os/log.h>
}
#endif
VCMI_LIB_NAMESPACE_BEGIN
namespace vstd
{
CLoggerBase::~CLoggerBase() = default;
CTraceLogger::CTraceLogger(const CLoggerBase * logger, const std::string & beginMessage, const std::string & endMessage)
: logger(logger), endMessage(endMessage)
{
logger->trace(beginMessage);
}
2017-08-12 13:36:04 +02:00
CTraceLogger::~CTraceLogger()
{
logger->trace(endMessage);
}
}//namespace vstd
const std::string CLoggerDomain::DOMAIN_GLOBAL = "global";
CLoggerDomain::CLoggerDomain(std::string name) : name(std::move(name))
{
if (this->name.empty())
throw std::runtime_error("Logger domain cannot be empty.");
}
CLoggerDomain CLoggerDomain::getParent() const
{
if(isGlobalDomain())
return *this;
2023-02-14 23:35:06 +02:00
const size_t pos = name.find_last_of('.');
if(pos != std::string::npos)
return CLoggerDomain(name.substr(0, pos));
return CLoggerDomain(DOMAIN_GLOBAL);
}
bool CLoggerDomain::isGlobalDomain() const { return name == DOMAIN_GLOBAL; }
const std::string& CLoggerDomain::getName() const { return name; }
2023-04-11 16:11:14 +02:00
std::recursive_mutex CLogger::smx;
std::recursive_mutex CLogManager::smx;
DLL_LINKAGE vstd::CLoggerBase * logGlobal = CLogger::getGlobalLogger();
DLL_LINKAGE vstd::CLoggerBase * logBonus = CLogger::getLogger(CLoggerDomain("bonus"));
DLL_LINKAGE vstd::CLoggerBase * logNetwork = CLogger::getLogger(CLoggerDomain("network"));
DLL_LINKAGE vstd::CLoggerBase * logAi = CLogger::getLogger(CLoggerDomain("ai"));
DLL_LINKAGE vstd::CLoggerBase * logAnim = CLogger::getLogger(CLoggerDomain("animation"));
2017-08-26 04:06:47 +02:00
DLL_LINKAGE vstd::CLoggerBase * logMod = CLogger::getLogger(CLoggerDomain("mod"));
CLogger * CLogger::getLogger(const CLoggerDomain & domain)
{
TLockGuardRec _(smx);
CLogger * logger = CLogManager::get().getLogger(domain);
if(!logger) // Create new logger
{
logger = new CLogger(domain);
if(domain.isGlobalDomain())
2016-10-02 20:21:20 +02:00
{
logger->setLevel(ELogLevel::TRACE);
2016-10-02 20:21:20 +02:00
}
CLogManager::get().addLogger(logger);
2016-10-02 20:21:20 +02:00
if (logGlobal != nullptr)
{
2016-10-03 20:32:01 +02:00
logGlobal->debug("Created logger %s", domain.getName());
2016-10-02 20:21:20 +02:00
}
}
return logger;
}
CLogger * CLogger::getGlobalLogger()
{
return getLogger(CLoggerDomain(CLoggerDomain::DOMAIN_GLOBAL));
}
CLogger::CLogger(const CLoggerDomain & domain) : domain(domain)
{
if(domain.isGlobalDomain())
{
level = ELogLevel::TRACE;
parent = nullptr;
}
else
{
level = ELogLevel::NOT_SET;
parent = getLogger(domain.getParent());
}
}
void CLogger::log(ELogLevel::ELogLevel level, const std::string & message) const
{
if(getEffectiveLevel() <= level)
callTargets(LogRecord(domain, level, message));
}
2016-11-28 18:34:20 +02:00
void CLogger::log(ELogLevel::ELogLevel level, const boost::format & fmt) const
{
try
{
log(level, fmt.str());
}
catch(...)
{
2023-01-08 18:23:25 +02:00
log(ELogLevel::ERROR, "Invalid log format!");
2016-11-28 18:34:20 +02:00
}
}
ELogLevel::ELogLevel CLogger::getLevel() const
{
TLockGuard _(mx);
return level;
}
void CLogger::setLevel(ELogLevel::ELogLevel level)
{
TLockGuard _(mx);
if (!domain.isGlobalDomain() || level != ELogLevel::NOT_SET)
this->level = level;
}
const CLoggerDomain & CLogger::getDomain() const { return domain; }
void CLogger::addTarget(std::unique_ptr<ILogTarget> && target)
{
TLockGuard _(mx);
targets.push_back(std::move(target));
}
ELogLevel::ELogLevel CLogger::getEffectiveLevel() const
{
for(const CLogger * logger = this; logger != nullptr; logger = logger->parent)
if(logger->getLevel() != ELogLevel::NOT_SET)
return logger->getLevel();
// This shouldn't be reached, as the root logger must have set a log level
return ELogLevel::INFO;
}
void CLogger::callTargets(const LogRecord & record) const
{
TLockGuard _(mx);
for(const CLogger * logger = this; logger != nullptr; logger = logger->parent)
2023-02-14 23:35:06 +02:00
for(const auto & target : logger->targets)
target->write(record);
}
void CLogger::clearTargets()
{
TLockGuard _(mx);
targets.clear();
}
bool CLogger::isDebugEnabled() const { return getEffectiveLevel() <= ELogLevel::DEBUG; }
bool CLogger::isTraceEnabled() const { return getEffectiveLevel() <= ELogLevel::TRACE; }
CLogManager & CLogManager::get()
{
TLockGuardRec _(smx);
static CLogManager instance;
return instance;
}
CLogManager::CLogManager() = default;
CLogManager::~CLogManager()
{
for(auto & i : loggers)
delete i.second;
}
void CLogManager::addLogger(CLogger * logger)
{
TLockGuard _(mx);
loggers[logger->getDomain().getName()] = logger;
}
CLogger * CLogManager::getLogger(const CLoggerDomain & domain)
{
TLockGuard _(mx);
auto it = loggers.find(domain.getName());
if(it != loggers.end())
return it->second;
else
return nullptr;
}
2016-10-02 20:21:20 +02:00
std::vector<std::string> CLogManager::getRegisteredDomains() const
{
std::vector<std::string> domains;
2023-02-14 23:35:06 +02:00
domains.reserve(loggers.size());
for(const auto & pair : loggers)
2016-10-02 20:21:20 +02:00
{
domains.push_back(pair.second->getDomain().getName());
}
return domains;
2016-10-02 20:21:20 +02:00
}
CLogFormatter::CLogFormatter()
: CLogFormatter("%m")
{
}
2023-02-14 23:35:06 +02:00
CLogFormatter::CLogFormatter(std::string pattern):
pattern(std::move(pattern))
{
}
std::string CLogFormatter::format(const LogRecord & record) const
{
std::string message = pattern;
//Format date
// boost::algorithm::replace_first(message, "%d", boost::posix_time::to_simple_string (record.timeStamp));
2016-08-12 14:51:14 +02:00
//Format log level
std::string level;
switch(record.level)
{
case ELogLevel::TRACE:
level = "TRACE";
break;
case ELogLevel::DEBUG:
level = "DEBUG";
break;
case ELogLevel::INFO:
level = "INFO";
break;
case ELogLevel::WARN:
level = "WARN";
break;
case ELogLevel::ERROR:
level = "ERROR";
break;
}
boost::algorithm::replace_first(message, "%l", level);
//Format name, thread id and message
boost::algorithm::replace_first(message, "%n", record.domain.getName());
boost::algorithm::replace_first(message, "%t", record.threadId);
boost::algorithm::replace_first(message, "%m", record.message);
boost::algorithm::replace_first(message, "%c", boost::posix_time::to_simple_string(record.timeStamp));
//return boost::to_string (boost::format("%d %d %d[%d] - %d") % dateStream.str() % level % record.domain.getName() % record.threadId % record.message);
return message;
}
void CLogFormatter::setPattern(const std::string & pattern) { this->pattern = pattern; }
void CLogFormatter::setPattern(std::string && pattern) { this->pattern = std::move(pattern); }
const std::string & CLogFormatter::getPattern() const { return pattern; }
CColorMapping::CColorMapping()
{
// Set default mappings
auto & levelMap = map[CLoggerDomain::DOMAIN_GLOBAL];
levelMap[ELogLevel::TRACE] = EConsoleTextColor::GRAY;
levelMap[ELogLevel::DEBUG] = EConsoleTextColor::WHITE;
levelMap[ELogLevel::INFO] = EConsoleTextColor::GREEN;
levelMap[ELogLevel::WARN] = EConsoleTextColor::YELLOW;
levelMap[ELogLevel::ERROR] = EConsoleTextColor::RED;
}
void CColorMapping::setColorFor(const CLoggerDomain & domain, ELogLevel::ELogLevel level, EConsoleTextColor::EConsoleTextColor color)
{
assert(level != ELogLevel::NOT_SET);
map[domain.getName()][level] = color;
}
EConsoleTextColor::EConsoleTextColor CColorMapping::getColorFor(const CLoggerDomain & domain, ELogLevel::ELogLevel level) const
{
CLoggerDomain currentDomain = domain;
while(true)
{
const auto & loggerPair = map.find(currentDomain.getName());
if(loggerPair != map.end())
{
const auto & levelMap = loggerPair->second;
const auto & levelPair = levelMap.find(level);
if(levelPair != levelMap.end())
return levelPair->second;
}
if (currentDomain.isGlobalDomain())
break;
currentDomain = currentDomain.getParent();
}
throw std::runtime_error("failed to find color for requested domain/level pair");
}
CLogConsoleTarget::CLogConsoleTarget(CConsoleHandler * console) :
2023-02-27 12:00:13 +02:00
#if !defined(VCMI_MOBILE)
2023-01-08 18:23:25 +02:00
console(console),
#endif
2023-01-08 18:23:25 +02:00
threshold(ELogLevel::INFO), coloredOutputEnabled(true)
{
formatter.setPattern("%m");
}
void CLogConsoleTarget::write(const LogRecord & record)
{
if(threshold > record.level)
return;
std::string message = formatter.format(record);
#ifdef VCMI_ANDROID
2023-01-08 18:23:25 +02:00
__android_log_write(ELogLevel::toAndroid(record.level), ("VCMI-" + record.domain.getName()).c_str(), message.c_str());
2021-03-13 12:47:06 +02:00
#elif defined(VCMI_IOS)
2022-08-15 15:31:58 +02:00
os_log_type_t type;
switch (record.level)
{
case ELogLevel::TRACE:
type = OS_LOG_TYPE_DEBUG;
break;
case ELogLevel::DEBUG:
type = OS_LOG_TYPE_DEFAULT;
break;
case ELogLevel::INFO:
type = OS_LOG_TYPE_INFO;
break;
case ELogLevel::WARN:
type = OS_LOG_TYPE_ERROR;
break;
case ELogLevel::ERROR:
type = OS_LOG_TYPE_FAULT;
break;
default:
return;
}
os_log_t currentLog;
static std::unordered_map<std::string, decltype(currentLog)> logs;
const auto& domainName = record.domain.getName();
auto logIt = logs.find(domainName);
if (logIt != logs.end())
currentLog = logIt->second;
else
{
2022-08-15 15:29:11 +02:00
currentLog = os_log_create(iOS_utils::bundleIdentifier(), domainName.c_str());
2022-08-15 15:31:58 +02:00
logs.insert({domainName, currentLog});
}
os_log_with_type(currentLog, type, "%{public}s", message.c_str());
#else
const bool printToStdErr = record.level >= ELogLevel::WARN;
if(console)
{
const EConsoleTextColor::EConsoleTextColor textColor =
coloredOutputEnabled ? colorMapping.getColorFor(record.domain, record.level) : EConsoleTextColor::DEFAULT;
2016-08-12 14:51:14 +02:00
console->print(message, true, textColor, printToStdErr);
}
else
{
TLockGuard _(mx);
if(printToStdErr)
std::cerr << message << std::endl;
else
std::cout << message << std::endl;
}
#endif
}
bool CLogConsoleTarget::isColoredOutputEnabled() const { return coloredOutputEnabled; }
void CLogConsoleTarget::setColoredOutputEnabled(bool coloredOutputEnabled) { this->coloredOutputEnabled = coloredOutputEnabled; }
ELogLevel::ELogLevel CLogConsoleTarget::getThreshold() const { return threshold; }
void CLogConsoleTarget::setThreshold(ELogLevel::ELogLevel threshold) { this->threshold = threshold; }
const CLogFormatter & CLogConsoleTarget::getFormatter() const { return formatter; }
void CLogConsoleTarget::setFormatter(const CLogFormatter & formatter) { this->formatter = formatter; }
const CColorMapping & CLogConsoleTarget::getColorMapping() const { return colorMapping; }
void CLogConsoleTarget::setColorMapping(const CColorMapping & colorMapping) { this->colorMapping = colorMapping; }
2023-02-14 23:35:06 +02:00
CLogFileTarget::CLogFileTarget(const boost::filesystem::path & filePath, bool append):
file(filePath, append ? std::ios_base::app : std::ios_base::out)
{
// formatter.setPattern("%d %l %n [%t] - %m");
formatter.setPattern("%l %n [%t] - %m");
}
void CLogFileTarget::write(const LogRecord & record)
{
std::string message = formatter.format(record); //formatting is slow, do it outside the lock
TLockGuard _(mx);
file << message << std::endl;
}
const CLogFormatter & CLogFileTarget::getFormatter() const { return formatter; }
void CLogFileTarget::setFormatter(const CLogFormatter & formatter) { this->formatter = formatter; }
2020-05-17 10:21:49 +02:00
CLogFileTarget::~CLogFileTarget()
{
file.close();
}
VCMI_LIB_NAMESPACE_END