Modify Java Thread Name
October 6, 2010
Part of my application generates a unique jobid for a given thread. I wanted to add that unique key to the thread name so that log4j debugging would show it, and we could work out which job the thread processed.
Here's the code I used to add the jobid to the thread:
String lExistingThreadName = Thread.currentThread().getName(); if (lExistingThreadName.indexOf("@#") > -1) { lExistingThreadName = lExistingThreadName.substring(0, lExistingThreadName.indexOf("@#")); } StringBuffer lNewThreadName = new StringBuffer(lExistingThreadName); lNewThreadName.append("@#"); lNewThreadName.append(lJobId); Thread.currentThread().setName(lNewThreadName.toString());
This was then logged using %t in the following log4j config:
<appender name="A1" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="logs/made-broker-lender-edl-pdi.log"/> <param name="Append" value="true"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{DATE} %-5p %t %C{2} - %m%n" /> </layout> </appender>