今天在配置log4j2.xml 测试使用RollingFileAppender 时 出现下面错误:
2016-03-30 14:45:12,669 main ERROR Unable to invoke factory method in class class org.apache.logging.log4j.core.appender.RollingFileAppender for element RollingFile.
2016-03-30 14:45:12,671 main ERROR Null object returned for RollingFile in Appenders.
2016-03-30 14:45:12,676 main ERROR Unable to locate appender "RollingFile" for logger config "root"
log4j2配置文件如下:
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN"> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) 此时对应 logger level 也应设置 为 trace--> <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %l - %msg%n" /> </Console> <File name="ApplicationLog" fileName="logs/app.log"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </File>
<RollingFile name="RollingFile" fileName="logs/app.log" filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz"> <PatternLayout> <Pattern>%d %p %c{1.} [%t] %m%n</Pattern> </PatternLayout> <Policies> <TimeBasedTriggeringPolicy /> <SizeBasedTriggeringPolicy size="1 MB"/> </Policies> <DefaultRolloverStrategy max="20"/> </RollingFile> </Appenders> <Loggers> <Root level="debug"> <AppenderRef ref="RollingFile"/> <AppenderRef ref="Console" /> <!-- <AppenderRef ref="ApplicationLog" /> --> </Root> </Loggers> </Configuration>
错误原因:自己在配置RollingFileAppender 时,将filename 配置同之前的 FileAppender 相同了,在loggers只将对应的fileAppender 引用注释掉(如上代码),但log4j在初始化时仍将配置读入,配置RollingFileAppender 时不要配置与其他 FileAppender 相同位置名称的filename。
所以此处应将对应的FileAppender 注释 ,或将RollingFileAppender的 filename 改为其他。
如还未解决可以参考:http://javahonk.com/unable-to-invoke-factory-method-in-class-class-org-apache-logging-log4j-core-appender-rollingfileappender/
或 官网 https://logging.apache.org/log4j/2.x/manual/appenders.html#RollingFileAppender