Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log Process id using Log4cxx or log4j

Tags:

log4j

log4cxx

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,

like image 980
CRK Avatar asked Nov 26 '10 14:11

CRK


1 Answers

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.

like image 75
skiphoppy Avatar answered Sep 20 '22 17:09

skiphoppy