动机
程序开发时,往往只需要在控制台打印日志。但是很多日志库(如Boost.Log)虽然提供很多功能,但集成起来比较麻烦。所以需要一个功能简单,能快速集成,外部依赖少的日志库。
代码
ConsoleLog.hpp
#ifndef __CONSOLE_LOG_HPP_ad91ca04_0cb8_44a5_a9b2_90bbeeaf46e9__
#define __CONSOLE_LOG_HPP_ad91ca04_0cb8_44a5_a9b2_90bbeeaf46e9__
#include <atomic>
#include <ctime>
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <string>
#include <thread>
namespace TinyLog {
using namespace std;
class ConsoleLog
{
public:
enum class ELevel {
eFatal = 3,
eError = 2,
eWarn = 1,
eInfo = 0,
eDebug = -1,
eTrace = -2,
};
private:
const string currentTime() {
time_t timer;
char buffer[26];
struct tm* tm_info;
timer = time(NULL);
#pragma warning(suppress : 4996)
tm_info = localtime(&timer);
strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
return buffer;
}
#define DEF_LOG_FUNC(funName, eLvl) \
void funName(const string & sMsg, const string & sFilePath, \
const decltype(__LINE__) nLnNo, const string & sFunNm) { \
if (m_eLvl > eLvl) { \
return; \
} else { /* do nothing */ } \
\
cout << "[" << currentTime() << "] " \
<< "[" << m_sName << "] " \
<< "[" << setw(5) << setfill(' ') << ""#funName"" << "] " \
<< "[T " << this_thread::get_id() << "] " \
<< "[" << sFilePath << ":" << nLnNo << "] " \
<< "[" << sFunNm << "] " \
<< sMsg << endl; \
}
public:
ConsoleLog(const char * pName) : m_sName(pName) {}
void setLevel(const ELevel eLvl) { m_eLvl = eLvl; }
const ELevel level() const { return m_eLvl; }
const char * version() { return m_sVer; }
DEF_LOG_FUNC(fatal, ELevel::eFatal);
DEF_LOG_FUNC(error, ELevel::eError);
DEF_LOG_FUNC(warn, ELevel::eWarn);
DEF_LOG_FUNC(info, ELevel::eInfo);
DEF_LOG_FUNC(debug, ELevel::eDebug);
DEF_LOG_FUNC(trace, ELevel::eTrace);
#define LOG_FATAL(logger, sMsg) logger.fatal((sMsg), __FILE__, __LINE__, __FUNCTION__);
#define LOG_ERROR(logger, sMsg) logger.error((sMsg), __FILE__, __LINE__, __FUNCTION__);
#define LOG_WARN(logger, sMsg) logger.warn ((sMsg), __FILE__, __LINE__, __FUNCTION__);
#define LOG_INFO(logger, sMsg) logger.info ((sMsg), __FILE__, __LINE__, __FUNCTION__);
#define LOG_DEBUG(logger, sMsg) logger.debug((sMsg), __FILE__, __LINE__, __FUNCTION__);
#define LOG_TRACE(logger, sMsg) logger.trace((sMsg), __FILE__, __LINE__, __FUNCTION__);
private:
atomic<ELevel> m_eLvl = ELevel::eInfo;
const string m_sName;
const char * m_sVer = "1.0.0.0";
};
}
#endif // !__CONSOLE_LOG_HPP_ad91ca04_0cb8_44a5_a9b2_90bbeeaf46e9__
main.cpp
#include "ConsoleLog.hpp"
#include <iostream>
int main()
{
TinyLog::ConsoleLog logger("MyLogger");
logger.setLevel(TinyLog::ConsoleLog::ELevel::eDebug);
LOG_FATAL(logger, "fatal message");
LOG_ERROR(logger, "error message");
LOG_WARN(logger, "warn message");
LOG_INFO(logger, "info message");
LOG_DEBUG(logger, "debug message");
LOG_TRACE(logger, "trace message");
}