#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定义。
参考资料:
1、glog功能介绍
网友评论