如何使用Log4cxx或log4j记录进程ID[英] How to log Process id using Log4cxx or log4j

本文是小编为大家收集整理的关于如何使用Log4cxx或log4j记录进程ID的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在使用 log4cxx 我的项目,我可以使用 [%t] 标记记录当前线程 ID,如何在其中记录进程 ID 或 log4j?.

我正在使用 ConversionPattern &基于xml的配置文件.

谢谢,

推荐答案

根据上面的回答,我打算在log4j中这样做:

import java.lang.management.*;
import org.apache.log4j.MDC;

private String getPID() {
  RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
  return rt.getName();
}

private void configLog4j() {
  // call this from somewhere before you start logging
  MDC.put("PID", getPID());
}

然后在我的 log4j.properties 中:

log4j.appender.FILE.layout.ConversionPattern=%d %X{PID} [%t] %p %c{1} %x - %m%n

这实际上会产生一个由 ID 号和主机名组成的 PID,至少在我的 Java 实现中,并且从我读到的内容可能是特定于实现的.你可以更进一步,只拆分 PID.

本文地址:https://www.itbaoku.cn/post/1574882.html

问题描述

I am using log4cxx my project and i can able to log current thread id using [%t] marker, how to log process id in it or log4j?.

I am using ConversionPattern & xml based configuration file.

Thanks,

推荐答案

Based on the above answers, I'm going to do this in log4j as follows:

import java.lang.management.*;
import org.apache.log4j.MDC;

private String getPID() {
  RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
  return rt.getName();
}

private void configLog4j() {
  // call this from somewhere before you start logging
  MDC.put("PID", getPID());
}

Then in my log4j.properties:

log4j.appender.FILE.layout.ConversionPattern=%d %X{PID} [%t] %p %c{1} %x - %m%n

This will actually yield a PID that consists of the ID number and the hostname, at least on my implementation of Java, and from what I read that could be implementation specific. You could go further and split out just the PID.

相关标签/搜索