您可以使用映射的诊断上下文解决您的问题:
import org.slf4j.MDC;
public class Main {
public static void main(String... args) {
// put process ID early
MDC.put("process_id",
ManagementFactory.getRuntimeMXBean().getName());
}
}
之后,您只需要按如下方式重新定义您的模式:
<pattern>{..., "process_id": "%X{process_id}"}</pattern>
编辑
您也可以创建自己的编码器和转换器,并在以下位置使用它们:logback.xml
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
public class ExtendedPatternLayoutEncoder extends PatternLayoutEncoder {
@Override
public void start() {
// put your converter
PatternLayout.defaultConverterMap.put(
"process_id", ProcessIdConverter.class.getName());
super.start();
}
}
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import java.lang.management.ManagementFactory;
public class ProcessIdConverter extends ClassicConverter {
private static final String PROCESS_ID =
ManagementFactory.getRuntimeMXBean().getName();
@Override
public String convert(final ILoggingEvent event) {
// for every logging event return processId from mx bean
// (or better alternative)
return PROCESS_ID;
}
}
<encoder class="some.package.ExtendedPatternLayoutEncoder">
<pattern>{..., "process_id": "%process_id"}</pattern>
</encoder>
完整示例:
<encoder class="some.package.ExtendedPatternLayoutEncoder">
<pattern>%d{dd.MM.yyyy HH:mm:ss.SSS} PID:%process_id [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>