log4j2: Include PID

天涯浪子 提交于 2019-12-04 05:42:55
Paul Vargas

Perhaps MDC can help you. Try this:

Java:

import java.lang.management.ManagementFactory;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;

public class TestPID {

    private static final Logger LOG = LogManager.getLogger(TestPID.class);

    static {
        // Get the process id
        String pid = ManagementFactory.getRuntimeMXBean().getName().replaceAll("@.*", "");

        // MDC
        ThreadContext.put("pid", pid);
    }

    public static void main(String[] args) {
        LOG.info("Testing...");
    }

}

XML:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d %5X{pid} %-5p %c#%M - %m%n" />
    </Console>
  </Appenders>
  <Loggers>
    <Root level="info">
      <AppenderRef ref="Console" />
    </Root>
  </Loggers>
</Configuration>

Output:

2014-09-10 00:13:49,281  7164 INFO  TestPID#main - Testing...
                         ↑↑↑↑
                    That's the PID

You may want to see:

There is a plugin ProcessIdPatternConverter in log4j2-core since version 2.9 that does exactly this.

just setting %pid or %processId in the pattern layout logs it.

log4j documentation: https://logging.apache.org/log4j/2.x/manual/layouts.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!