How do I dynamically create log file names in log4j2 using MDC
Asked Answered
C

1

6

I'm trying to generate different log files based on values passed through the MDC in log4j . Having tried several approaches, I cant get any to work .

Here's how I'm going about it .

Within java code . I'm setting a bunch of values within the 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))   
            }
        }
    }

Within log4j2.xml, I'm trying 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 of appid, uid are populated correctly based on the passed in http header(through the MDC). However, I expect the log file name to be special.log but the file is generated as ${ctx:APPNAME}.log

I've also tried setting APPNAME by doing System.setProperty("APPNAME","special") and referencing it using ${sys:APPNAME} but I fail to get the expected result.

Any thoughts on how I could fix this would be greatly appreciated.

Chignon answered 27/8, 2015 at 6:43 Comment(2)
I can't see the complete configuration of the routing appender. Without that info I am not really sure what you are doing.Suggestive
See https://mcmap.net/q/957544/-how-to-log-multiple-threads-in-different-log-filesExcitement
T
0

Not sure I understand everything about the question, but you can do this:

    /* 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();      

(the ctx.reconfigure() is important)

and then use it in the log4j2.xml like this:

filePattern="${sys:SomeProperty}"

does that help?

I suppose you already saw this: http://logging.apache.org/log4j/2.x/faq.html#separate_log_files

Trustworthy answered 27/8, 2015 at 13:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.