部署:
1、安装log4cpp,执行如下指令进行编译安装
log4cpp的官网是:
http://log4cpp.sourceforge.net/wget https://nchc.dl.sourceforge.net/project/log4cpp/log4cpp-1.1.x%20%28new%29/log4cpp-1.1/log4cpp-1.1.3.tar.gz tar xzvf log4cpp-1.1.3.tar.gz cd log4cpp-1.1.3 ./configure make make install
安装完毕后,log4cpp库路径在 /usr/local/lib、头文件路径在 /usr/local/include/log4cpp
可以使用命令 mv 拷贝到自己的项目路径中去;例如,创建一个lib文件夹,将刚刚安装的log4cpp的lib库文件拷贝到此文件夹中。
头文件同理。
示例1:
创建 test.conf:日志的配置文件#include <log4cpp/Category.hh> #include <log4cpp/FileAppender.hh> #include <log4cpp/PatternLayout.hh> #include <log4cpp/OstreamAppender.hh> #include <log4cpp/PropertyConfigurator.hh>#define LOG(__level) log4cpp::Category::getRoot() << log4cpp::Priority::__level << __FILE__ << " " << __LINE__ << ": "int main() {log4cpp::PropertyConfigurator::configure("log4cpp.conf");log4cpp::Category &root = log4cpp::Category::getRoot();root.setPriority(log4cpp::Priority::INFO);LOG(DEBUG) << "i am happy.";LOG(INFO) << "oh, you happy, we happy.";LOG(NOTICE)<< "please do not contact me. ";LOG(WARN) << "i am very busy now.";LOG(ERROR) << "oh, what happed?";return 0; }
#定义Root category的属性 log4cpp.rootCategory=DEBUG, RootLog#定义RootLog属性 log4cpp.appender.RootLog=RollingFileAppender log4cpp.appender.RootLog.layout=PatternLayout #log4cpp.appender.RootLog.layout.ConversionPattern=%d{% m-%d %H:%M:%S %l} [%t][%p]%m%n log4cpp.appender.RootLog.layout.ConversionPattern=%d{%m-%d %H:%M:%S %l} [%t][%p]%m%n#日志位置:自定义 log4cpp.appender.RootLog.fileName=/root/log/test/dry.log log4cpp.appender.RootLog.maxFileSize=268435456 #256MB log4cpp.appender.RootLog.fileNamePattern=dry_%i.log log4cpp.appender.RootLog.maxBackupIndex=256
示例2:
#include <log4cpp/Category.hh> #include <log4cpp/FileAppender.hh> #include <log4cpp/PatternLayout.hh> #include <log4cpp/OstreamAppender.hh> #include <log4cpp/PropertyConfigurator.hh>#define LOG(__level) log4cpp::Category::getRoot() << log4cpp::Priority::__level << __FILE__ << " " << __LINE__ << ": "int main() {// 输出到std::cout 控制台//log4cpp::Appender *appender = new log4cpp::OstreamAppender("root", &std::cout);// 配置日志输出到当前目录的 log.log 日志文件中log4cpp::Appender *appender = new log4cpp::FileAppender("root", "log.log");appender->setLayout(new log4cpp::BasicLayout());log4cpp::PatternLayout *patternLayout = new log4cpp::PatternLayout();patternLayout->setConversionPattern("%d [%p] - %m%n");appender->setLayout(patternLayout);log4cpp::Category &root = log4cpp::Category::getRoot();root.setPriority(log4cpp::Priority::INFO);root.addAppender(appender);LOG(DEBUG) << "i am happy.";LOG(INFO) << "oh, you happy, we happy.";LOG(NOTICE)<< "please do not contact me. ";LOG(WARN) << "i am very busy now.";LOG(ERROR) << "oh, what happed?";return 0; }
解释:
category:设置类别输出
priority: 日志优先级 --> 低于该级别的日志不会被记录
( DEBUG < INFO < NOTICE < WARN < ERROR < FATAL )