Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing thread name using java.util.logging

Tags:

java

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.

like image 589
Majid Alfifi Avatar asked Jul 31 '11 11:07

Majid Alfifi


People also ask

Is Java Util logging thread safe?

All methods on Logger are multi-thread safe. Note that separate calls from different threads can still be interleaved. It just means that you won't have one message being interrupted and sliced by the other.

Does Java Util logging use Log4j?

The JDK Logging Adapter is a custom implementation of java. util. logging. LogManager that uses Log4j.

What is Java Util logger?

A Logger object is used to log messages for a specific system or application component. Loggers are normally named, using a hierarchical dot-separated namespace. Logger names can be arbitrary strings, but they should normally be based on the package name or class name of the logged component, such as java.net or javax.

How do you write a logger in Java?

The process of creating a new Logger in Java is quite simple. You have to use Logger. getLogger() method. The getLogger() method identifies the name of the Logger and takes string as a parameter.


1 Answers

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.

like image 130
Tomasz Nurkiewicz Avatar answered Oct 07 '22 01:10

Tomasz Nurkiewicz