如何定义Log4j2 appender只记录特定的命名logger?

时间:2016-10-26 07:03:57

标签: java logging log4j log4j2

private static final Logger log = LogManager.getLogger(ABC.class); private static final Logger resultLog = LogManager.getLogger("ResultLog");

我们如何定义只能记录特定于“ResultLog”记录器的appender?

我当前的Log4j2.xml文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="ABC" packages="">
    <Appenders>
        <RollingFile name="RollingFile" fileName="logs/ABC.log"
                     filePattern="logs/$${date:yyyy-MM}/ABC-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout>
                <Pattern>%d [%t] %p %c{1.} %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="250 MB"/>
            </Policies>
        </RollingFile>
        <File name="resultFile" fileName="logs/result.log">
            <PatternLayout pattern="%m%n"/>
        </File>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d [%t] %p %c{1.} %m%n"/>
        </Console>
    </Appenders>

    <Loggers>
        <Root level="debug">
            <AppenderRef ref="RollingFile"/>
            <AppenderRef ref="Console"/>
            <AppenderRef ref="resultFile"/>
        </Root>
    </Loggers>
</Configuration>

感谢

1 个答案:

答案 0 :(得分:2)

添加

<Logger name="ResultLog">
  <AppenderRef ...>
</Logger>

到Loggers标签。

您可以参考本手册:https://logging.apache.org/log4j/2.x/manual/configuration.html#XML