Java print stack trace to log | Logger class

To print a stack trace to log you Should declare logger and method info(e.toString()) or log(Level.INFO, e.toString()). Logging is the process of writing log messages during the execution of a program to get an error and warning messages as well as info messages.

The java.util.logging package provides the logging capabilities via the Logger class.

In general, at the top of every class, you should have:

Now, you can just use various facilities of the Logger class.

There are many examples and also different types of logging. Take a look at the java.util.logging package.

Example code: Java print stack trace to log

See the below exception handling example and print the exception message in the log.

Output:

Java print stack trace to log

Logger log methods levels:-

The log levels define the severity of a message. The Level class is used to define which messages should be written to the log.

The following lists the Log Levels in descending order:

  • SEVERE (highest)
  • WARNING
  • INFO
  • CONFIG
  • FINE
  • FINER
  • FINEST

In addition to that, you can also use the levels OFF and ALL to turn the logging off or to log everything.

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java print stack trace to log codes are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.