Java – how to use MDC to dynamically create log file names in log4j 2

I'm trying to generate different log files based on the values passed through MDC in log4j After trying several methods, I couldn't work

This is how I do it

In 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'm trying to route the log to the corresponding file through execution<

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 and uid are correctly populated according to the incoming HTTP header (through MDC) However, I want the log file name to be special Log, but the file is generated as ${CTX: appName} log

I also tried to execute system Setproperty ("appName", "special") sets appName and references it with ${sys: appName}, but I didn't get the expected results

Any ideas on how I can solve this problem will be appreciated

Solution

I'm not sure I understand everything about this, 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();

(CTX. Reconfigure() is important)

Then in log4j2 Use it in XML as follows:

filePattern="${sys:SomeProperty}"

Does this help?

I think you've seen this: http://logging.apache.org/log4j/2.x/faq.html#separate_log_files

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>