You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
121 lines
2.1 KiB
121 lines
2.1 KiB
#include "logger.h"
|
|
|
|
#include <cstdio>
|
|
#include <ctime>
|
|
#include <sys/time.h>
|
|
|
|
namespace mtx {
|
|
|
|
Logger & Logger::instance()
|
|
{
|
|
static Logger s_logger;
|
|
return s_logger;
|
|
}
|
|
|
|
void Logger::setLevel(LogLevel level)
|
|
{
|
|
m_level = level;
|
|
}
|
|
|
|
void Logger::setDestinations(bool toStdout, const std::string & file)
|
|
{
|
|
std::lock_guard<std::mutex> lock(m_mutex);
|
|
m_toStdout = toStdout;
|
|
m_file = file;
|
|
}
|
|
|
|
void Logger::log(LogLevel level, const char * fmt, ...)
|
|
{
|
|
va_list ap;
|
|
va_start(ap, fmt);
|
|
vlog(level, fmt, ap);
|
|
va_end(ap);
|
|
}
|
|
|
|
void Logger::vlog(LogLevel level, const char * fmt, va_list ap)
|
|
{
|
|
if (level < m_level)
|
|
{
|
|
return;
|
|
}
|
|
static const char * s_tags[] = {"DEB", "INF", "WAR", "ERR"};
|
|
char tLine[2048];
|
|
time_t tNow = time(nullptr);
|
|
struct tm tTm;
|
|
localtime_r(&tNow, &tTm);
|
|
int tLen = (int) strftime(tLine, sizeof(tLine), "%Y/%m/%d %H:%M:%S ", &tTm);
|
|
tLen += snprintf(tLine + tLen, sizeof(tLine) - tLen, "%s ", s_tags[(int) level]);
|
|
if (tLen < (int) sizeof(tLine))
|
|
{
|
|
int tN = vsnprintf(tLine + tLen, sizeof(tLine) - tLen, fmt, ap);
|
|
tLen = (tN < 0) ? tLen : tLen + tN;
|
|
}
|
|
if (tLen > (int) sizeof(tLine) - 2)
|
|
{
|
|
tLen = (int) sizeof(tLine) - 2;
|
|
}
|
|
tLine[tLen++] = '\n';
|
|
tLine[tLen] = 0;
|
|
|
|
std::lock_guard<std::mutex> lock(m_mutex);
|
|
if (m_toStdout)
|
|
{
|
|
fwrite(tLine, 1, tLen, stdout);
|
|
fflush(stdout);
|
|
}
|
|
if (! m_file.empty())
|
|
{
|
|
FILE * tF = fopen(m_file.c_str(), "a");
|
|
if (tF != nullptr)
|
|
{
|
|
fwrite(tLine, 1, tLen, tF);
|
|
fclose(tF);
|
|
}
|
|
}
|
|
}
|
|
|
|
void LogParent::log(LogLevel level, const char * fmt, ...) const
|
|
{
|
|
Logger & tL = Logger::instance();
|
|
if (level < tL.level())
|
|
{
|
|
return;
|
|
}
|
|
char tMsg[1800];
|
|
va_list ap;
|
|
va_start(ap, fmt);
|
|
vsnprintf(tMsg, sizeof(tMsg), fmt, ap);
|
|
va_end(ap);
|
|
tL.log(level, "%s%s", m_prefix.c_str(), tMsg);
|
|
}
|
|
|
|
LogLevel parseLogLevel(const std::string & s, bool * ok)
|
|
{
|
|
if (ok)
|
|
{
|
|
*ok = true;
|
|
}
|
|
if (s == "debug")
|
|
{
|
|
return LogLevel::Debug;
|
|
}
|
|
if (s == "info")
|
|
{
|
|
return LogLevel::Info;
|
|
}
|
|
if (s == "warn")
|
|
{
|
|
return LogLevel::Warn;
|
|
}
|
|
if (s == "error")
|
|
{
|
|
return LogLevel::Error;
|
|
}
|
|
if (ok)
|
|
{
|
|
*ok = false;
|
|
}
|
|
return LogLevel::Info;
|
|
}
|
|
|
|
} // namespace mtx
|