上一篇文章已经教了大家如何编译log4cpp,下边就是教大家如何把log4cpp应用到具体的自己的项目中。
头文件包含于lib库引入等操作默认大家都会,就不详细介绍了,如果大家有疑问欢迎大家留言
1、配置文件准备
# log4cpp.properties
log4cpp.rootCategory=DEBUG, rootAppender
log4cpp.category.sub1=DEBUG, A1, A2
log4cpp.category.sub1.sub2=DEBUG, A3
log4cpp.appender.rootAppender=ConsoleAppender
log4cpp.appender.rootAppender.layout=PatternLayout
log4cpp.appender.rootAppender.layout.ConversionPattern=%d [%p] %m%n
log4cpp.appender.A1=FileAppender
log4cpp.appender.A1.fileName=A1.log
log4cpp.appender.A1.layout=BasicLayout
log4cpp.appender.A2=FileAppender
log4cpp.appender.A2.threshold=WARN
log4cpp.appender.A2.fileName=A2.log
log4cpp.appender.A2.layout=PatternLayout
log4cpp.appender.A2.layout.ConversionPattern=%d [%p] %m%n
log4cpp.appender.A3=RollingFileAppender
log4cpp.appender.A3.fileName=A3.log
log4cpp.appender.A3.maxFileSize=200
log4cpp.appender.A3.maxBackupIndex=1
log4cpp.appender.A3.layout=PatternLayout
log4cpp.appender.A3.layout.ConversionPattern=%d [%p] %m%n
2、demo代码
// main.cpp
#include #include int main(int argc, char* argv[])
{
std::string initFileName = "log4cpp.properties";
log4cpp::PropertyConfigurator::configure(initFileName);
log4cpp::Category& root = log4cpp::Category::getRoot();
log4cpp::Category& sub1 =
log4cpp::Category::getInstance(std::string("sub1"));
log4cpp::Category& sub2 =
log4cpp::Category::getInstance(std::string("sub1.sub2"));
root.warn("Storm is coming");
sub1.debug("Received storm warning");
sub1.info("Closing all hatches");
sub2.debug("Hiding solar panels");
sub2.error("Solar panels are blocked");
sub2.debug("Applying protective shield");
sub2.warn("Unfolding protective shield");
sub2.info("Solar panels are shielded");
sub1.info("All hatches closed");
root.info("Ready for storm.");
log4cpp::Category::shutdown();
return 0;
}
3、输出结果
2012-11-14 18:44:58,163 [WARN] Storm is coming
2012-11-14 18:44:58,166 [DEBUG] Received storm warning
2012-11-14 18:44:58,170 [INFO] Closing all hatches
2012-11-14 18:44:58,172 [DEBUG] Hiding solar panels
2012-11-14 18:44:58,175 [ERROR] Solar panels are blocked
A3.log.1
2012-11-14 18:44:58,179 [DEBUG] Applying protective shield
2012-11-14 18:44:58,183 [WARN] Unfolding protective shield
2012-11-14 18:44:58,186 [INFO] Solar panels are shielded
2012-11-14 18:44:58,190 [INFO] All hatches closed
2012-11-14 18:44:58,192 [INFO] Ready for storm.
4、相关文章链接