javalogging

Printing thread name using java.util.logging


Is it possible to print the thread name in the log statements generated by java.util.logging.Logger?

One alternative is to do something like the following:

logger.info(thread.getName() + " some useful info");

but it's repetitive and the logging framework should handle it.


Solution

  • Embarrassingly, but looks like java.util.logging can't do this...

    The default java.util.logging.SimpleFormatter doesn't have the ability to log thread name at all. The java.util.logging.FileHandler supports few template placeholders, none of them is thread name.

    java.util.logging.XMLFormatter is the closest one, but only logs thread id:

    <record>
      <date>2011-07-31T13:15:32</date>
      <millis>1312110932680</millis>
      <sequence>0</sequence>
      <logger></logger>
      <level>INFO</level>
      <class>java.util.logging.LogManager$RootLogger</class>
      <method>log</method>
      <thread>10</thread>
      <message>Test</message>
    </record>
    

    If you think we're getting close - we're not. LogRecord class only holds the thread ID, not its name - not very useful.