C++日志系统log4cxx

安装

yum安装

直接使用yum安装log4cxx.x86_64(库文件) log4cxx-devel.x86_64(头文件)

yum install log4cxx.x86_64       # 库文件
yum install log4cxx-devel.x86_64 # 头文件

源码安装

log4cxx的编译依赖于apr和apr-util这两个组件。
从http://archive.apache.org/dist/apr/下载这两个依赖组件的源码包。
从https://logging.apache.org/log4cxx/latest_stable/download.html下载log4cxx源码包。
附apr(Apache Portable Runtime)官网。

# 编译安装apr
tar -zxvf apr-1.5.2.tar.gz
cd apr-1.5.2
./configure --prefix=/usr/local
make
make install

# 编译安装apr-util
tar -zxvf apr-util-1.5.4.tar.gz
cd apr-util-1.5.4
./configure --prefix=/usr/local --with-apr=/usr/local
make
make install

# 编译安装log4cxx
tar -zxvf apache-log4cxx-0.10.0.tar.gz
cd apache-log4cxx-0.10.0
vim src/main/cpp/inputstreamreader.cpp  #增加#include
vim src/main/cpp/socketoutputstream.cpp #增加#include
vim src/examples/cpp/console.cpp        #增加#include及#include 
./configure --prefix=/usr/local --with-charset=utf-8 --with-apr=/usr/local --with-apr-util=/usr/local
make
make install

# 将log4cxx动态库所在文件夹加入搜索路径
vim ~/.bashrc
添加 export LD_LIBRARY_PATH=/usr/local/lib
source ~/.bashrc

编译apr-util遇到如下问题,可能缺expat的开发库,安装expat库试试:yum install expat-devel

xml/apr_xml.c:35:19: fatal error: expat.h: No such file or directory
 #include 

示例

配置文件log4cxx.properties

#设置rootlogger为DEBUG级别,使用了ca和fa两个Appender
log4j.rootLogger=DEBUG,ca, fa

#对Appenderfa进行设置:
#这是一个文件类型的Appender,
#其输出文件(File)为./output.log,
#输出方式(Append)为覆盖方式,
#输出格式(layout)为PatternLayout
log4j.appender.fa=org.apache.log4j.FileAppender
log4j.appender.fa.File=./output.log
log4j.appender.fa.Append=false
log4j.appender.fa.layout=org.apache.log4j.PatternLayout
log4j.appender.fa.layout.ConversionPattern=%d[%t] %-5p %.16c - %m%n

#对Appenderca进行设置:
#这是一个控制台类型的Appender
#输出格式(layout)为PatternLayout
log4j.appender.ca=org.apache.log4j.ConsoleAppender
log4j.appender.ca.layout=org.apache.log4j.PatternLayout
log4j.appender.ca.layout.ConversionPattern=%d[%t] %-5p %.16c - %m%n

示例代码main.cpp

#include 
#include 
#include 

using namespace log4cxx;

int main()
{
    PropertyConfigurator::configure("./log4cxx.properties");

    LoggerPtr rootLogger = Logger::getRootLogger();

    LOG4CXX_TRACE(rootLogger,"TRACE");
    LOG4CXX_DEBUG(rootLogger, "DEBUG");
    LOG4CXX_WARN(rootLogger, "WARN");
    LOG4CXX_ERROR(rootLogger, "ERROR");

    return 0;
}

编译执行

# 编译
g++ -o main main.cpp -llog4cxx
# 执行
./main
# 输出
2018-06-10 15:52:08,610[0x7f5d68bf6880] DEBUG root - DEBUG
2018-06-10 15:52:08,610[0x7f5d68bf6880] WARN  root - WARN
2018-06-10 15:52:08,610[0x7f5d68bf6880] ERROR root - ERROR

你可能感兴趣的:(C/C++)