然后就是在Makefile中添加上与log4cxx相关的一切东西,包括头文件路径,库文件路径等。如果你编译的时候看到与log4cxx相关的“undefined reference …”的错误,那么肯定是没有找到相关的库文件或头文件,这里需要提醒你的是要添加的几个库文件参数:-llog4cxx,-lapr-1,-laprutil-1。
你把上面的步骤都做好了,这个时候,你再编译你的程序,可能又会遇到以下错误(好吧,的确有点折磨人):
./lib/log4cxx/libaprutil-1.a(apr_xml.o): In function `apr_xml_parser_geterror':
/home/log4cxx/apr-util-1.3.12/xml/apr_xml.c:478: undefined reference to `XML_ErrorString'
./lib/log4cxx/libaprutil-1.a(apr_xml.o): In function `do_parse':
/home/log4cxx/apr-util-1.3.12/xml/apr_xml.c:418: undefined reference to `XML_Parse'
/home/log4cxx/apr-util-1.3.12/xml/apr_xml.c:422: undefined reference to `XML_GetErrorCode'
./lib/log4cxx/libaprutil-1.a(apr_xml.o): In function `cleanup_parser':
/home/log4cxx/apr-util-1.3.12/xml/apr_xml.c:344: undefined reference to `XML_ParserFree'
./lib/log4cxx/libaprutil-1.a(apr_xml.o): In function `apr_xml_parser_create':
/home/log4cxx/apr-util-1.3.12/xml/apr_xml.c:381: undefined reference to `XML_ParserCreate'
/home/log4cxx/apr-util-1.3.12/xml/apr_xml.c:390: undefined reference to `XML_SetUserData'
/home/log4cxx/apr-util-1.3.12/xml/apr_xml.c:391: undefined reference to `XML_SetElementHandler'
/home/log4cxx/apr-util-1.3.12/xml/apr_xml.c:392: undefined reference to `XML_SetCharacterDataHandler'
/home/log4cxx/apr-util-1.3.12/xml/apr_xml.c:404: undefined reference to `XML_SetDefaultHandler'
collect2: ld returned 1 exit status
make: *** [cpsAPI] Error 1
这些乱七八糟的东西是怎么回事?据网上的一些文章说,这是 libaprutil 的一个bug,它不会自动链接到它的依赖项,从而导致了那些错误。要解决这个问题,你在编译的时候添加 -lexpat 参数即可——无论你是在Makefile中,还是在命令行直接用g++命令编译程序,都必须要带上这个参数,否则就会得到上面的那一堆错误(真让人恼火啊)。
这样,总算全部搞定了,程序可以编译通过了,下面,就是如何使用log4cxx来写日志的问题了,简单地说一下。在你需要写日志的类的文件中(例如MyClass.cpp),include两个log4cxx头文件:log4cxx.h和propertyconfigurator.h,然后在类的外部添加:
static log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("MyClass.cpp"));
然后在需要写日志之前,先加载log4cxx的配置文件(其实也可以不使用配置文件的,这里假设你要使用自定义的配置文件):
log4cxx::PropertyConfigurator::configure("./log4cxx.properties"); 这里指定了log4cxx.properties文件作为log4cxx的配置文件(文件名不一定是要叫log4cxx.properties), 在这个文件中定义了各种参数,例如日志文件会写到哪里去,日志的格式等等。具体的格式可以很复杂、功能很强大,这里无法给出一个详细的说明,后面会给出一个简单的文件示例。然后就可以写日志了,例如: LOG4CXX_INFO(logger, "Test info message."); LOG4CXX_ERROR(logger, "Test error message.");运行程序,看看日志是否写进去了?写进去的话就说明成功了。
上面所说的log4cxx.properties文件,给一个例子如下:
log4j.rootLogger=debug, R log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout # Pattern to output the caller's file name and line number. log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p (%F:%L) %c - %m%n log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=./app.log log4j.appender.R.MaxFileSize=200KB # Keep one backup file log4j.appender.R.MaxBackupIndex=10 log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p (%F:%L) %c - %m%n |
附:【使用log4cxx遇到的一些问题记录】
(1)IO Exception : status code =28
这个错误可能是由于磁盘空间满了造成的,log4cxx无法将日志写入磁盘上,请看这个链接。
