Java logging thread name

Printing Thread Info in Log File Using Log4j2

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

This tutorial will show the idea and examples of logging thread information using the Log4j2 library.

2. Logging and Threads

Logs are a powerful tool to provide the context about what was happening in the system when some error or flow occurred. Logging helps us capture and persist relevant information to be analyzed at any time.

Threads allow our application to execute multiple things simultaneously to handle more requests and make our jobs more efficient.

Many Java applications use logging and threads to control their process in this scenario. However, as the logs usually concentrate on a specific file, the logs mess up from different threads, and the user cannot identify and understand the sequence of the events. We will use one of the most popular Java logging frameworks, Log4j2, to show relevant information about our thread to solve this problem.

3. Log4j2 Usage

Forward, we have an example of using some parameters in Log4j2 to show information about our thread:

 %d --- thread_id="%tid" thread_name="%tn" thread_priority="%tp" --- [%p] %m%n 

Log4j2 uses parameters in its pattern to refer to data. All parameters start with a % in their beginner. Here are some examples of thread parameters:

  • tid: Thread identifier is a positive long number generated when the thread is created.
  • tn: It’s a sequence of characters that names a thread.
  • tp: Thread priority is an integer number between 1 and 10 where more significant numbers mean higher priority.

First, as it suggests, we are adding the information’s about the id, name, and priority of our thread. Therefore, to visualize it, we need to create a simple application that makes new threads and log some info:

public class Log4j2ThreadInfo < private static final Logger logger = LogManager.getLogger(Log4j2ThreadInfo.class); public static void main(String[] args) < IntStream.range(0, 5).forEach(i -> < Runnable runnable = () ->logger.info("Logging info"); Thread thread = new Thread(runnable); thread.start(); >); > >

In other words, we are simply running a forEach in a range of 0 to 5 with the help of Java Streams and then starting a new thread with some logging. As a result, we’re going to have:

2022-01-14 23:44:56.893 --- thread_id="22" thread_name="Thread-2" thread_priority="5" --- [INFO] Logging info 2022-01-14 23:44:56.893 --- thread_id="21" thread_name="Thread-1" thread_priority="5" --- [INFO] Logging info 2022-01-14 23:44:56.893 --- thread_id="20" thread_name="Thread-0" thread_priority="5" --- [INFO] Logging info 2022-01-14 23:44:56.893 --- thread_id="24" thread_name="Thread-4" thread_priority="5" --- [INFO] Logging info 2022-01-14 23:44:56.893 --- thread_id="23" thread_name="Thread-3" thread_priority="5" --- [INFO] Logging info

4. Conclusion

This article shows a simple way to add thread information in your Java Project using Log4j2 Parameters. If you want to check the code up, it is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Printing thread name using java.util.logging

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:

 2011-07-31T13:15:32 1312110932680 0 INFO java.util.logging.LogManager$RootLogger log 10 Test  

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

Solution 2

With a custom Formatter

Luckily, LogRecord contains the ID of the thread that produced the log message. We can get hold of this LogRecord when writing a custom Formatter . Once we have that, we only need to get the thread name via its ID.

There are a couple of ways to get the Thread object corresponding to that ID, here’s mine:

static Optional getThread(long threadId) < return Thread.getAllStackTraces().keySet().stream() .filter(t ->t.getId() == threadId) .findFirst(); > 

The following is a minimal Formatter that only prints the thread name and the log message:

private static Formatter getMinimalFormatter() < return new Formatter() < @Override public String format(LogRecord record) < int threadId = record.getThreadID(); String threadName = getThread(threadId) .map(Thread::getName) .orElseGet(() ->"Thread with ID " + threadId); return threadName + ": " + record.getMessage() + "\n"; > >; > 

To use your custom formatter, there are again different options, one way is to modify the default ConsoleHandler :

public static void main(final String. args) < getDefaultConsoleHandler().ifPresentOrElse( consoleHandler ->consoleHandler.setFormatter(getMinimalFormatter()), () -> System.err.println("Could not get default ConsoleHandler")); Logger log = Logger.getLogger(MyClass.class.getName()); log.info("Hello from the main thread"); SwingUtilities.invokeLater(() -> log.info("Hello from the event dispatch thread")); > static Optional getDefaultConsoleHandler() < // All the loggers inherit configuration from the root logger. See: // https://docs.oracle.com/javase/8/docs/technotes/guides/logging/overview.html#a1.3 var rootLogger = Logger.getLogger("") // The root logger's first handler is the default ConsoleHandler return first(Arrays.asList(rootLogger.getHandlers())); >static Optional first(List list)

Your minimal Formatter should then produce the folowing log messages containing the thread name:

main: Hello from the main thread

AWT-EventQueue-0: Hello from the event dispatch thread

This is a Formatter that shows how to log more than thread name and log message:

private static Formatter getCustomFormatter() < return new Formatter() < @Override public String format(LogRecord record) < var dateTime = ZonedDateTime.ofInstant(record.getInstant(), ZoneId.systemDefault()); int threadId = record.getThreadID(); String threadName = getThread(threadId) .map(Thread::getName) .orElse("Thread with ID " + threadId); // See also: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Formatter.html var formatString = "%1$tF %1$tT %2$-7s [%3$s] %4$s.%5$s: %6$s %n%7$s"; return String.format( formatString, dateTime, record.getLevel().getName(), threadName, record.getSourceClassName(), record.getSourceMethodName(), record.getMessage(), stackTraceToString(record) ); >>; > private static String stackTraceToString(LogRecord record) < final String throwableAsString; if (record.getThrown() != null) < var stringWriter = new StringWriter(); var printWriter = new PrintWriter(stringWriter); printWriter.println(); record.getThrown().printStackTrace(printWriter); printWriter.close(); throwableAsString = stringWriter.toString(); >else < throwableAsString = ""; >return throwableAsString; > 

That Formatter produces log messages like these:

2019-04-27 13:21:01 INFO [AWT-EventQueue-0] package.ClassName.method: The log message

Solution 3

Some application servers implicitly log the thread ID (I know of WebSphere). You can create your own LogFormatter. The records passed to the formatter contain the Thread ID, see here. I implemented that approach for Tomcat several times, but it’ll work in Java SE environments as well.

BTW: The Thread name is not available to LogRecord.

Solution 4

java.util.logging has many curious peculiarities. you can add a facade API to tweak its behaviors

public class Log Logger logger; static public Log of(Class clazz) return new Log( Logger.getLogger( clazz.getName() )); public void error(Throwable thrown, String msg, Object. params) < log(ERROR, thrown, msg, params); >void log(Level level, Throwable thrown, String msg, Object. params) < if( !logger.isLoggable(level) ) return; // bolt on thread name somewhere LogRecord record = new LogRecord(. ); record.setXxx(. ); . logger.log(record); >---- static final Log log = Log.of(Foo.class); . log.error(. ); 

People use java’s logging mostly because they don’t want to have 3rd party dependencies. That’s also why they can’t depend on existing logging facades like apache’s or slf4j.

Solution 5

I had similar problem. As answered here How to align log messages using java.util.logging you can extend java.util.logging.Formatter but instead getting LogRecord#getThreadID() you can get thread name by invoking Thread.currentThread().getName() like this:

public class MyLogFormatter extends Formatter < private static final MessageFormat messageFormat = new MessageFormat("[  ] \n"); public MyLogFormatter() < super(); >@Override public String format(LogRecord record) < Object[] arguments = new Object[6]; arguments[0] = record.getLoggerName(); arguments[1] = record.getLevel(); arguments[2] = Thread.currentThread().getName(); arguments[3] = new Date(record.getMillis()); arguments[4] = record.getMessage(); arguments[5] = record.getSourceMethodName(); return messageFormat.format(arguments); >> 

Источник

Printing thread name using java.util.logging

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:

 2011-07-31T13:15:32 1312110932680 0 INFO java.util.logging.LogManager$RootLogger log 10 Test  

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

With a custom Formatter

Luckily, LogRecord contains the ID of the thread that produced the log message. We can get hold of this LogRecord when writing a custom Formatter . Once we have that, we only need to get the thread name via its ID.

There are a couple of ways to get the Thread object corresponding to that ID, here’s mine:

static Optional getThread(long threadId) < return Thread.getAllStackTraces().keySet().stream() .filter(t ->t.getId() == threadId) .findFirst(); > 

The following is a minimal Formatter that only prints the thread name and the log message:

private static Formatter getMinimalFormatter() < return new Formatter() < @Override public String format(LogRecord record) < int threadId = record.getThreadID(); String threadName = getThread(threadId) .map(Thread::getName) .orElseGet(() ->"Thread with ID " + threadId); return threadName + ": " + record.getMessage() + "\n"; > >; > 

To use your custom formatter, there are again different options, one way is to modify the default ConsoleHandler :

public static void main(final String. args) < getDefaultConsoleHandler().ifPresentOrElse( consoleHandler ->consoleHandler.setFormatter(getMinimalFormatter()), () -> System.err.println("Could not get default ConsoleHandler")); Logger log = Logger.getLogger(MyClass.class.getName()); log.info("Hello from the main thread"); SwingUtilities.invokeLater(() -> log.info("Hello from the event dispatch thread")); > static Optional getDefaultConsoleHandler() < // All the loggers inherit configuration from the root logger. See: // https://docs.oracle.com/javase/8/docs/technotes/guides/logging/overview.html#a1.3 var rootLogger = Logger.getLogger("") // The root logger's first handler is the default ConsoleHandler return first(Arrays.asList(rootLogger.getHandlers())); >static Optional first(List list)

Your minimal Formatter should then produce the folowing log messages containing the thread name:

main: Hello from the main thread

AWT-EventQueue-0: Hello from the event dispatch thread

This is a Formatter that shows how to log more than thread name and log message:

private static Formatter getCustomFormatter() < return new Formatter() < @Override public String format(LogRecord record) < var dateTime = ZonedDateTime.ofInstant(record.getInstant(), ZoneId.systemDefault()); int threadId = record.getThreadID(); String threadName = getThread(threadId) .map(Thread::getName) .orElse("Thread with ID " + threadId); // See also: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Formatter.html var formatString = "%1$tF %1$tT %2$-7s [%3$s] %4$s.%5$s: %6$s %n%7$s"; return String.format( formatString, dateTime, record.getLevel().getName(), threadName, record.getSourceClassName(), record.getSourceMethodName(), record.getMessage(), stackTraceToString(record) ); >>; > private static String stackTraceToString(LogRecord record) < final String throwableAsString; if (record.getThrown() != null) < var stringWriter = new StringWriter(); var printWriter = new PrintWriter(stringWriter); printWriter.println(); record.getThrown().printStackTrace(printWriter); printWriter.close(); throwableAsString = stringWriter.toString(); >else < throwableAsString = ""; >return throwableAsString; > 

That Formatter produces log messages like these:

2019-04-27 13:21:01 INFO [AWT-EventQueue-0] package.ClassName.method: The log message

Источник

Читайте также:  Поиск на странице
Оцените статью