How to log Process id using Log4cxx or log4j

CRK picture CRK · Nov 26, 2010 · Viewed 10.5k times · Source

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,

Answer

skiphoppy picture skiphoppy · Aug 30, 2012

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.