1.下載好log4cpp開源庫後,添加到工程中,調整編譯順序。
2.在工程目錄中添加log.property配置文件,文件內容如下:
# property configurator file
# PriorityLevel
# EMERG = 0, FATAL = 0, ALERT = 100, CRIT = 200,
# ERROR = 300, WARN = 400, NOTICE = 500, INFO = 600,
# DEBUG = 700, NOTSET = 800
log4cpp.rootCategory=WARN
log4cpp.category.TestLog=INFO, Log
log4cpp.appender.TestLog=RollingFileAppender
log4cpp.appender.TestLog.fileName=log\MyTest.log
log4cpp.appender.TestLog.maxFileSize=8000000
log4cpp.appender.TestLog.maxBackupIndex=8
log4cpp.appender.TestLog.layout=PatternLayout
log4cpp.appender.TestLog.layout.ConversionPattern=%d{%Y-%m-%d %H:%M:%S %l}[%t] [%p]: %m%n
#以上的fileName可以是絕對路徑也可是相對路徑,
#注意,如若是相對路徑,當對於一個自啓動的exe來說此處可能引起write的crash!!!
3. cpp中的相關code
// 添加頭文件
#include <log4cpp/Category.hh>
#include <log4cpp/PropertyConfigurator.hh>
//添加Current function的宏定義
#ifndef CUR_FUNC
#define CUR_FUNC (FUNCTION“, “) //此處function兩邊都有兩個下劃線
#endif //CUR_FUNC
//在初始化函數裏添加初始化log4cpp的code:
try
{
string strLogFileName += "...\log.property"; //此處爲log.property的絕對路徑
log4cpp::PropertyConfigurator::configure(strLogFileName );
}
catch(log4cpp::ConfigureFailure & f)
{
std::ostringstream errinfo;
errinfo << "Configure Problem " << f.what() << std::endl;
std::cout << errinfo.str();
}
//寫log
log4cpp::Category& log = log4cpp::Category::getInstance("Log");//注意此處的Log對應上面log.property文件中的log4cpp.category.TestLog=INFO, Log
log.info(CUR_FUNC“this is test log!”); //此log是否打印取決於log4cpp.category.TestLog=INFO, Log中的INFO等級,如果配置中將INFO改爲ERROR,則此log不打印。
基本用法已介紹完畢。
當然也可以用另一種方法實現,即創建一個專門寫log的類,在工程中統一調用此類的接口。
一般可以寫如下函數:
void CTestLog::Write_Log(LPCTSTR szFormat, ...)
{
va_list argList;
va_start( argList, szFormat );
CString strLog;
strLog.FormatV(szFormat, argList);
va_end( argList );
string sLog = strLog.GetString();
Write_Log(sLog);
}
第一次用markdown的編譯器 字體大小不會調~ 尤其帶#
OVER THX 2017/3/1