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) {
if (headers != null) {
Map<String, String> clonedHeaders =
new HashMap<String, String>(headers);
LogMasker.getInstance().maskHeaders(clonedHeaders);
clonedHeaders.put("APPNAME", "special");
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>
</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.
, , .