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.