log4j2:包含PID [英] log4j2: Include PID

查看:603
本文介绍了log4j2:包含PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用log4j2,同时在不同的进程(即不同的JVM)中运行相同代码的多个实例。我希望所有进程都能记录到同一个文件,interleaved如何配置(通过log4j2.xml)输出PID,以便在日志中区分不同的进程?

I'm using log4j2, and running multiple instances of the same code in different processes (ie different JVMs) at the same time. I'd like all processes to log to the same file, interleaved How can I configure (via log4j2.xml) to output the PID, so that the different processes can be distinguished in the logs?

推荐答案

或许 MDC 可以帮到你。试试这个:

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>

输出

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






您可能希望看到:


You may want to see:

  • Layouts - PatternLayout
  • Effective Logging in Java/JEE – Mapped Diagnostic Context
  • How can a Java program get its own process ID?
  • How to use MDC with thread pools?

这篇关于log4j2:包含PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆