一、log4cpp概念
Category: 写日志。
Appender: 指定日志的目的地。
Layout: 设定日志的格式。
Priority: 指定Category的优先级和日志的优先级。
NDC: 嵌套的上下文诊断,可用于多线程、多场景的跟踪调试。
优先级:NOTSET < DEBUG < INFO < NOTICE < WARN < ERROR < CRIT < ALERT < FATAL = EMERG
当日志优先级高于Category的优先级时,该日志被记录,否则被忽略。
二、示例代码(Windows/Linux)
2.1 代码
#include
using namespace std;
#include
#include
#include
#include
#include
#include
int main()
{
//Step 1 实例化Layout对象、Appender对象、Category对象
log4cpp::Layout *layout = new log4cpp::BasicLayout;
log4cpp::Appender *appender = new log4cpp::OstreamAppender("default", &std::cout);
//log4cpp::Appender *appender = new log4cpp::FileAppender("File", "test.txt");
log4cpp::Category &log = log4cpp::Category::getInstance("test");
//Step 2 把Layout对象附着到Appender对象上,把Appender对象附着到Category对象上
appender->setLayout(layout);
log.addAppender(appender);
//Step 3 设置Category的优先级
log.setPriority(log4cpp::Priority::DEBUG);
log.alert("DEBUG emerg.");
log.log(log4cpp::Priority::ALERT, "DEBUG alert.");
log.error("DEBUG error.");
log.info("DEBUG warn.");
log.log(log4cpp::Priority::INFO, "DEBUG info.");
log.debug("DEBUG debug.");
//
log.setPriority(log4cpp::Priority::ERROR);
log.alert("ERROR emerg.");
log.log(log4cpp::Priority::ALERT, "ERROR alert.");
log.error("ERROR error.");
log.info("ERROR warn.");
log.log(log4cpp::Priority::INFO, "ERROR info.");
log.debug("ERROR debug.");
log4cpp::Category::shutdown();
return 0;
}
2.2 输出结果
windows下:
Linux下: