log4cpp用法

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值