为了能将log4j的ConversionPattern无缝应用到logback上来,需要对两个Conversion做适配,具体可以参考:Log4j 与 Logback的ConversionPattern对比
ch.qos.logback.classic.PatternLayout
static代码块新增:
// adapter for log4j
defaultConverterMap.put("l", LocationConverter.class.getName());
defaultConverterMap.put("x", NDCConverter.class.getName());
其中:
public class LocationConverter extends ClassicConverter {
@Override
public String convert(ILoggingEvent le) {
StringBuilder buf = new StringBuilder();
StackTraceElement[] cda = le.getCallerData();
if (cda != null && cda.length > 0) {
buf.append(cda[0]);
return buf.toString();
} else {
return CallerData.CALLER_DATA_NA;
}
}
}
public class NDCConverter extends ClassicConverter {
@Override
public String convert(ILoggingEvent event) {
Map<String, String> mdcPropertyMap = event.getMDCPropertyMap();
return outputMDCForAllKeys(mdcPropertyMap);
}
private String outputMDCForAllKeys(Map<String, String> mdcPropertyMap) {
StringBuilder buf = new StringBuilder();
Map<Integer, String> ndcMap = new HashMap<Integer, String>();
for (Map.Entry<String, String> entry : mdcPropertyMap.entrySet()) {
if (entry.getKey().startsWith("NDC") && entry.getKey().length() > 3) {
String index = entry.getKey().substring(3);
try {
int idx = Integer.parseInt(index);
ndcMap.put(idx, entry.getValue());
} catch (Exception e) {
// ignore
}
}
}
boolean first = true;
for (int i = 0; i < ndcMap.size(); i++) {
if (first) {
first = false;
} else {
buf.append(" ");
}
buf.append(ndcMap.get(i));
}
return buf.toString();
}
}
NDCConverter只是兼容了输出,因为在logback里,NDC是通过MDC来实现的,其key为NDC + index(from 0),因此可以通过key来实现顺序输出,但是这个是基于用户的 MDC 不能以 "NDC"开头,再加上数字来命令,否则NDC的输出会出现MDC的内容;