How to write different logs in different files with log4j2 (MDC in xml)?

泪湿孤枕 提交于 2019-12-28 04:21:28

问题


Now I'm using structure like this: 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>

Logger:

    <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>

But it doesn't work with MDC keys. How could I use MDC keys in xml to config RollingFileAppender?


回答1:


Take a look at RoutingAppender. Maybe this can get you started:

<?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>


来源:https://stackoverflow.com/questions/17827923/how-to-write-different-logs-in-different-files-with-log4j2-mdc-in-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!