google glog的簡單封裝
阿新 • • 發佈:2019-02-12
#include <stdarg.h> #include <stdint.h> #include <string> #include <glog/logging.h> #include <glog/log_severity.h> using namespace std; #pragma comment(lib, "libglog_static.lib") class CGLog { public: CGLog(void) { memset(pLogBuff, 0, 2048); } ~CGLog(void) { // here, cannot free the object. /*if (NULL != m_pInstance) { delete m_pInstance; m_pInstance = NULL; }*/ } int32_t InitGLog(const int8_t * argv0, const int8_t * szLogFile = "./log", int32_t nLogSeverityToPrint = google::GLOG_WARNING, int32_t nLogSeverityToFile = google::GLOG_INFO) { CHECK_NOTNULL(szLogFile); google::InitGoogleLogging(argv0); google::SetLogDestination(nLogSeverityToFile, szLogFile); google::SetStderrLogging(nLogSeverityToPrint); return 0; } void GLogMsg(uint32_t nLogSeverity, const char *format, ...) { va_list arg_ptr; va_start(arg_ptr, format); vsprintf(pLogBuff, format, arg_ptr); switch(nLogSeverity) { case 0: DLOG(INFO) << pLogBuff; break; case 1: DLOG(WARNING) << pLogBuff; break; case 2: DLOG(ERROR) << pLogBuff; break; case 3: DLOG(FATAL) << pLogBuff; break; default: break; } va_end(arg_ptr); memset(pLogBuff, 0, 2048); } public: static CGLog * Instance() { if (NULL == m_pInstance) { m_pInstance = new CGLog(); } return m_pInstance; } private: static CGLog * m_pInstance; char pLogBuff[2048]; }; CGLog * CGLog::m_pInstance = NULL; #define LOGINIT(...) CGLog::Instance()->InitGLog(__VA_ARGS__); #define LOGINFO(...) CGLog::Instance()->GLogMsg(0, __VA_ARGS__); #define LOGERROR(...) CGLog::Instance()->GLogMsg(2, __VA_ARGS__); int _tmain(int argc, _TCHAR* argv[]) { LOGINIT(argv[0]); LOGINFO("First Number: %d.", 1); LOGERROR("Second Number: %d.", 2); return 0; }
演示效果如下:
注意,因glog的嚴重性級別中使用了ERROR巨集,與<windows.h>檔案中衝突,可通過以下兩種方式避免:
a.在包含<windows.h>檔案之前,定義巨集WIN32_LEAN_AND_MEAN 或者NOGDI;
b.在包含<windows.h>檔案之後,undef掉ERROR定義。