我需要在我的log4js日志中包含PID。我看到很多使用线程上下文的例子。但是,这些需要在创建的每个单独的线程上进行设置。我受到这样的限制。在不使用线程上下文的情况下记录log4j2中的PID
我需要一个解决方案,既不使用线程上下文,也可以为任何可能创建的线程设置所有线程上下文的PID。
我需要在我的log4js日志中包含PID。我看到很多使用线程上下文的例子。但是,这些需要在创建的每个单独的线程上进行设置。我受到这样的限制。在不使用线程上下文的情况下记录log4j2中的PID
我需要一个解决方案,既不使用线程上下文,也可以为任何可能创建的线程设置所有线程上下文的PID。
请在Log4j2 issue tracker上创建功能请求,以使其成为内置功能。
现在,您可以创建一个自定义插件。见下面的代码。这将允许您在pattern layout中指定%pid
(与消息的%m
类似)。
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
@Plugin(name = "ProcessIdPatternConverter", category = "Converter")
@ConverterKeys({ "pid", "processId" })
public final class ProcessIdPatternConverter extends LogEventPatternConverter {
private final String pid;
private ProcessIdPatternConverter(String[] options) {
super("Process ID", "pid");
String temp = options.length > 0 ? options[0] : "???";
try {
// likely works on most platforms
temp = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
} catch (final Exception ex) {
try {
// try a Linux-specific way
temp = new File("/proc/self").getCanonicalFile().getName();
} catch (final IOException ignoredUseDefault) {}
}
pid = temp;
}
/**
* Obtains an instance of ProcessIdPatternConverter.
*
* @param options users may specify a default like {@code %pid{NOPID} }
* @return instance of ProcessIdPatternConverter.
*/
public static ProcessIdPatternConverter newInstance(final String[] options) {
return new ProcessIdPatternConverter(options);
}
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
toAppendTo.append(pid);
}
}
查看manual了解更多关于Log4j2插件如何工作的细节。让Log4j2认识你的插件
一种方式是在配置的packages
属性指定插件类的包名称:(跟踪上Log4j2内部调试以帮助排除故障切换)
<Configuration status="trace"
packages="com.myorg.mypluginpackage">
我们已经为此添加了功能请求:https://issues.apache.org/jira/browse/LOG4J2-1884 – Matt