Categories
Coding

Process Ids and Log4J Appenders

If you ever need to create log files that are automatically prefixed by the process id of the native OS-level JVM process (or any other unique identifier for the VM process), it can be difficult, due to the lack of a straightforward mechanism in Java for obtaining the process handle or id. However, you can work around the limitation like this (JDK 1.5+ only):


import org.apache.log4j.FileAppender;

public class PidPrefixFileAppender extends FileAppender {
  
  @Override
  public void setFile(String file) {
    RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
    super.setFile(rt.getName() "-" + file);
  }

}


This will automatically prefix any log files created via this appender, for example:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

  <appender name="ConsoleAppender" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{DATE} %-5p %-15c (%F:%M:%L) – %m%n"/>
    </layout>
  </appender>
  
        <appender name="CacheLoadCsvAppender" class="co.uk.researchkitchen.PidPrefixFileAppender">
                <param name="File" value="cacheload.log"/>
                <layout class="org.apache.log4j.PatternLayout">
                     <param name="ConversionPattern" value="%m%n"/>
                </layout>
        </appender>

        <category name="cacheLoadLogger" additivity="false">
                <priority value="info"/>
                <appender-ref ref="CacheLoadCsvAppender"/>
        </category>
        
        
  <root>
    <priority value="info" />
  </root>

</log4j:configuration>

Will produce log files in the format processid@machine_id-cacheload.log.