Java怎样使用log4j2向不同文件中写入不同的日志?

标签: Java log4j2
发布时间: 2013/8/3 20:01:37

现在我是像下面代码的做法使用结构appender

<RollingFile name="user.log" append="true" fileName="users/%MDC{USERNAME}.txt"
                 filePattern="users/archive/%MDC{USERNAME}-%d{MM-dd-yyyy}-%i.txt.gz">
        <PatternLayout pattern="%-5p %d{MMMM-dd HH:mm:ss} %X: %c - %m%n"/>
        <Policies>
            <TimeBasedTriggeringPolicy/>
            <SizeBasedTriggeringPolicy size="50 MB"/>
        </Policies>
    </RollingFile>
<appender-ref ref="user.log">
    <ThreadContextMapFilter onMatch="ACCEPT" onMismatch="DENY" operator="or">
        <KeyValuePair key="USERNAME" value="%X{USERNAME}"/>
        <KeyValuePair key="IP" value="%X{IP}"/>
    </ThreadContextMapFilter>
</appender-ref>

但使用MDC key时不起作用。我如何使用xml的MDC key配置RollingFileAppender?

解决方法 1:

看看RoutingAppender,也许你能从这入手。

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="DEBUG" name="MyApp" packages="">
  <appenders>
    <Routing name="Routing">
      <Routes pattern="$${ctx:USERNAME}">
        <Route>
          <RollingFile name="user.log" append="true" fileName="users/${ctx:USERNAME}.txt"
             filePattern="users/archive/${ctx:USERNAME}-%d{MM-dd-yyyy}-%i.txt.gz">
            <PatternLayout>
              <pattern>%d{ISO8601} [%t] %p %c %L - %m%n</pattern>
            </PatternLayout>
            <Policies>
              <TimeBasedTriggeringPolicy/>
              <SizeBasedTriggeringPolicy size="50 MB"/>
            </Policies>
          </RollingFile>
        </Route>
      </Routes>
    </Routing>
  </appenders>
 
  <loggers>
    <root level="TRACE">
      <appender-ref ref="Routing" level="DEBUG" />
    </root>
  </loggers>
</configuration>


官方微信
官方QQ群
31647020