How to dynamically create log file names in log4j2 using MDC

I am trying to create different log files based on the values ​​passed through MDCin log4j. Having tried several approaches, I cannot get them to work.

This is how I do it.

Inside java code. I set a bunch of values ​​in MDC.

public static void addHeadersToMDC(Map<String, String> headers) {
       //headers contains other http headers such as uid,appid, client-type etc.

 if (headers != null) {
            Map<String, String> clonedHeaders =
                    new HashMap<String, String>(headers);
            LogMasker.getInstance().maskHeaders(clonedHeaders);
            clonedHeaders.put("APPNAME", "special");//setting APPNAME to MDC here.
            for (String header : clonedHeaders.keySet()) {
                ThreadContext.put(header, clonedHeaders.get(header))   
            }
        }
    }

In log4j2.xml, I try to route the logs to the appropriate file by doing <

Routing name="Routing">
             <Routes pattern="$${ctx:ROUTINGKEY}">
                <Route key="async-perf">
                     <RollingFile name="Rolling-Async-Perf" fileName="/usr/local/logs/${ctx:APPNAME}.log"
            filePattern="./logs/${date:yyyy-MM}/perf-%d{yyyy-MM-dd}-%i.log.gz"  immediateFlush="false">
            <PatternLayout charset="UTF-8">
                <pattern>%d LogLevel=%p my_appid=%X{appid} uid=%X{uid} class=%c %m%n</pattern><!-- These values are populated correctly-->
            </PatternLayout>

Here the values appidare uidfilled in correctly based on the transferred in the http header (via MDC). However, I expect the log file name to be special.log, but the file will be created as${ctx:APPNAME}.log

I also tried to configure APPNAME by executing System.setProperty("APPNAME","special")and referencing it with ${sys:APPNAME}, but I was not able to get the expected result.

, , .

+4
1

, , :

    /* Setting system property SomeProperty - used by log4j2 */
    System.setProperty("SomeProperty", "someValue");
    org.apache.logging.log4j.core.LoggerContext ctx = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
    ctx.reconfigure();      

( ctx.reconfigure())

log4j2.xml :

filePattern="${sys:SomeProperty}"

?

, : http://logging.apache.org/log4j/2.x/faq.html#separate_log_files

0

All Articles