本文介绍了如何使用log4j2(MDC in xml)在不同文件中写入不同的日志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在使用这样的结构:
Appender:

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>

记录器:

    <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密钥。我如何在xml中使用MDC键来配置RollingFileAppender?

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

推荐答案

看一下RoutingAppender。也许这可以让你开始:

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>

这篇关于如何使用log4j2(MDC in xml)在不同文件中写入不同的日志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 04:35