lokinet/include/llarp/logger.hpp

98 lines
2.1 KiB
C++
Raw Normal View History

2018-05-27 14:04:30 +00:00
#ifndef LLARP_LOGGER_HPP
#define LLARP_LOGGER_HPP
#include <ctime>
#include <iomanip>
2018-05-27 14:04:30 +00:00
#include <iostream>
#include <sstream>
#include <string>
2018-05-27 14:04:30 +00:00
namespace llarp
{
enum LogLevel
{
eLogDebug,
eLogInfo,
eLogWarn,
eLogError
};
struct Logger
{
LogLevel minlevel = eLogDebug;
std::ostream& out = std::cout;
};
extern Logger _glog;
void
SetLogLevel(LogLevel lvl);
2018-05-27 14:04:30 +00:00
/** internal */
template < typename TArg >
void
LogAppend(std::stringstream& ss, TArg&& arg) noexcept
2018-05-27 14:04:30 +00:00
{
ss << std::forward< TArg >(arg);
}
/** internal */
template < typename TArg, typename... TArgs >
void
LogAppend(std::stringstream& ss, TArg&& arg, TArgs&&... args) noexcept
2018-05-27 14:04:30 +00:00
{
LogAppend(ss, std::forward< TArg >(arg));
LogAppend(ss, std::forward< TArgs >(args)...);
}
/** internal */
template < typename... TArgs >
void
_Log(LogLevel lvl, const char* fname, TArgs&&... args) noexcept
2018-05-27 14:04:30 +00:00
{
if(_glog.minlevel > lvl)
2018-05-27 14:04:30 +00:00
return;
2018-06-06 12:46:26 +00:00
std::stringstream ss;
2018-05-27 14:04:30 +00:00
switch(lvl)
{
case eLogDebug:
ss << (char)27 << "[0m";
2018-05-27 14:04:30 +00:00
ss << "[DBG] ";
break;
case eLogInfo:
ss << (char)27 << "[1m";
2018-05-27 14:04:30 +00:00
ss << "[NFO] ";
break;
case eLogWarn:
ss << (char)27 << "[1;33m";
2018-05-27 14:04:30 +00:00
ss << "[WRN] ";
break;
case eLogError:
ss << (char)27 << "[1;31m";
2018-05-27 14:04:30 +00:00
ss << "[ERR] ";
break;
}
2018-06-06 12:46:26 +00:00
std::time_t t;
std::time(&t);
std::string tag = fname;
auto pos = tag.rfind('/');
if(pos != std::string::npos)
tag = tag.substr(pos + 1);
2018-06-06 12:46:26 +00:00
ss << std::put_time(std::localtime(&t), "%F %T") << " " << tag;
auto sz = tag.size() % 8;
while(sz--)
ss << " ";
ss << "\t";
2018-05-27 14:04:30 +00:00
LogAppend(ss, std::forward< TArgs >(args)...);
ss << (char)27 << "[0;0m";
_glog.out << ss.str() << std::endl;
2018-05-27 14:04:30 +00:00
}
}
#define Debug(x, ...) _Log(llarp::eLogDebug, __FILE__, x, ##__VA_ARGS__)
#define Info(x, ...) _Log(llarp::eLogInfo, __FILE__, x, ##__VA_ARGS__)
#define Warn(x, ...) _Log(llarp::eLogWarn, __FILE__, x, ##__VA_ARGS__)
#define Error(x, ...) _Log(llarp::eLogError, __FILE__, x, ##__VA_ARGS__)
2018-05-27 14:04:30 +00:00
#endif