5

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?

Remko Popma
  • 35,130
  • 11
  • 92
  • 114
ruslanys
  • 1,183
  • 2
  • 13
  • 25

1 Answers1

10

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>
Remko Popma
  • 35,130
  • 11
  • 92
  • 114
  • Thank you very much. But it is too late xD I've already found this solution by myself. Anyway thank you!) – ruslanys Jul 25 '13 at 03:48
  • @Remko Is there a way to print the logs if the context doesn't have the required key – Lalit Mehra Aug 20 '18 at 11:30
  • 1
    seems like .. https://logging.apache.org/log4j/log4j-2.1/faq.html has the answer to my question – Lalit Mehra Aug 20 '18 at 11:42
  • @ruslanys - What is the solution to the original problem? I am trying to print the transaction id (tid) using MDC in log4j2 framework but it is not printing the tid in the logs. Am i doing something wrong? Below is the snippet of my log4j2.xml file. – Ayaskant Feb 19 '19 at 14:08
  • This solution doesn't seem to be working. It gives me an error:- `Unable to locate appender "RollingFile" for logger config` – Chetan Oswal Mar 01 '20 at 07:56
  • @ruslanys were you able to get MDC keys in log4j2.xml? if yes, how? – Ashwani Oct 16 '20 at 11:39