#include "StdAfx.h"
#ifdef LOG4CPP_SHOW
#pragma comment(lib, "log4cpp.lib")
#include "Log.h"
#include "log4cpp\Category.hh"
#include <string>
#include "log4cpp\Appender.hh"
#include "log4cpp\Layout.hh"
#include "log4cpp\FileAppender.hh"
#include "log4cpp\BasicLayout.hh"
CLog* CLog::m_pInstance = NULL;
CLog::CLog(void)
{
//设置默认路径
CString csLogFilePath;
GetModuleFileName(NULL,csLogFilePath.GetBufferSetLength(MAX_PATH+1),MAX_PATH);
csLogFilePath.ReleaseBuffer();
int pos = csLogFilePath.ReverseFind('\\');
csLogFilePath = csLogFilePath.Left(pos);
CStringA tmpA(csLogFilePath);
m_strLogFilePath = tmpA.GetBuffer();
log4cpp::Appender* pFileAppender = new log4cpp::FileAppender("fileLog",m_strLogFilePath + "\\logForBEHoopsViewModule.log");
log4cpp::Layout* pLayout = new log4cpp::BasicLayout;
pFileAppender->setLayout(pLayout);
log4cpp::Category& root = log4cpp::Category::getRoot();
root.addAppender(pFileAppender);
root.setPriority(log4cpp::Priority::INFO);
}
CLog::~CLog(void)
{
log4cpp::Category::shutdown();
}
CLog* CLog::GetInstance()
{
if (!m_pInstance)
{
m_pInstance = new CLog;
static CLogObjCleaner cl;
}
return m_pInstance;
}
void CLog::info( const std::string& strInfo )
{
log4cpp::Category& root = log4cpp::Category::getRoot();
root.info(strInfo);
}
void CLog::info( const CString& csInfo )
{
CStringA tmpA(csInfo);
log4cpp::Category& root = log4cpp::Category::getRoot();
root.info(tmpA.GetBuffer());
}
#endif
本人愚拙,代码之中若有不妥,望见谅!
管理log的对象采用了单例模式。在对管理log类的定义,采用了利用预处理宏的方式,开关是否对其编译,并且考虑到需要和svn上的代码做同步,而有时候只是自己需要对log进行输出进行观察,所以导入库的方式使用命令 #pragma comment(lib, "log4cpp.lib"),使其包括在预处理命令之中,这样即使svn上没有对应的log4cpp库文件,只要预处理器不包含对应的定义,就不会出现编译错误。
log采用全局单例,所以编写了一个私有内部类对这个全局单例在程序退出时对其进行删除操作 -- static CLogObjCleaner cl;
当然,还有许多可以改进的地方,例如把初始化函数改为static CLog* GetInstance(std::string strFilePath = "", std::string strFileName = "", log4cpp::Priority::PriorityLevel ePriority = log4cpp::Priority::INFO);这样可以根据需要初始化log对象;还有就是增加 修改优先级的函数,增加添加不同的appender的函数等