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

1

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?

Yl answered 24/7, 2013 at 7:36 Comment(0)
O
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>
Overcritical answered 24/7, 2013 at 23:20 Comment(6)
Thank you very much. But it is too late xD I've already found this solution by myself. Anyway thank you!)Yl
@Remko Is there a way to print the logs if the context doesn't have the required keyShrill
seems like .. logging.apache.org/log4j/log4j-2.1/faq.html has the answer to my questionShrill
@Yl - 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. <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %c{1} %X{tid} %msg%n" />Bronchus
This solution doesn't seem to be working. It gives me an error:- Unable to locate appender "RollingFile" for logger configHavstad
@Yl were you able to get MDC keys in log4j2.xml? if yes, how?Eighth

© 2022 - 2024 — McMap. All rights reserved.