先看完整配置文件log4cxx.properties
log4j.additivity.gather = false
log4j.rootLogger= debug, R, stdout
//设置子logger
log4j.logger.Lib_a =debug, ap1, stdout
log4j.logger.Lib_b =debug, ap2, stdout
#设置不继承父Logger
log4j.additivity.Lib_a=false
log4j.additivity.Lib_b=false
log4j.appender.logfile.encoding=UTF-8
//标准输出,向控制台打印
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
//Root
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=./hello.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern==%d [%c]-[%p] %m%n
log4j.appender.ap1=org.apache.log4j.RollingFileAppender
log4j.appender.ap1.File=./hello_a.log
log4j.appender.ap1.MaxFileSize=100KB
log4j.appender.ap1.MaxBackupIndex=10
log4j.appender.ap1.layout=org.apache.log4j.PatternLayout
log4j.appender.ap1.layout.ConversionPattern==%d{yyyy-MM-dd} [%c]-[%p] %m%n
log4j.appender.ap2=org.apache.log4j.RollingFileAppender
log4j.appender.ap2.File=./hello_b.log
log4j.appender.ap2.MaxFileSize=100KB
log4j.appender.ap2.MaxBackupIndex=10
log4j.appender.ap2.layout=org.apache.log4j.PatternLayout
log4j.appender.ap2.layout.ConversionPattern==%d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n
// include log4cxx header files.
#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/propertyconfigurator.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
//LoggerPtr logger(Logger::getLogger("R"));
LoggerPtr logger_lib_a(Logger::getLogger("Lib_a"));
LoggerPtr logger_lib_b(Logger::getLogger("Lib_b"));
int main(int argc, char **argv)
{
try
{
// Set up a simple configuration that logs on the console.
PropertyConfigurator::configure("log4cxx.properties");
//LOG4CXX_INFO(logger, "test R")
LOG4CXX_DEBUG(logger_lib_a, "test R.a")
LOG4CXX_DEBUG(logger_lib_b, "test R.b")
}
catch(...)
{
}
return 0;
}
注意事项:
1.
log4j.rootLogger= debug, R, stdout
//设置子logger
log4j.logger.Lib_a =debug, ap1, stdout
log4j.logger.Lib_b =debug, ap2, stdout
在这里rootLogger,“L”要大写,下面设置子logger,“l”要小写,这个仿佛是log4cxx规定的。
2.
#设置不继承父Logger
log4j.additivity.Lib_a=false
log4j.additivity.Lib_b=false
这里一定要设置继承关系为非继承,否则子logger设置的属性就白设置了
3.
//设置子logger
log4j.logger.Lib_a =debug, ap1, stdout
log4j.logger.Lib_b =debug, ap2, stdout
子logger要加上stdout,否则会没有控制台打印,stdout设置如下
//标准输出,向控制台打印
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
4.
LoggerPtr logger_lib_a(Logger::getLogger("Lib_a"));
LoggerPtr logger_lib_b(Logger::getLogger("Lib_b"));
获取logger的时候一定要用append的名,如上。