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 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:
private final static Logger LOGGER = Logger.getLogger(MyClass.class.getName());
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.
import java.util.logging.Level; import java.util.logging.Logger; public class MyClass { private final static Logger LOGGER = Logger.getLogger(MyClass.class.getName()); public static void main(String[] args) { try { int a[] = new int[10]; a[11] = 30 / 0; } catch (Exception e) { LOGGER.log(Level.INFO,e.toString()); //OR (both works same) LOGGER.info(e.toString()); } System.out.println("Remain codes"); } }
Output:
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.
Nice! But this unfortunately only prints the exception’s message and _not_ the entire stack trace (as e.printStackTrace(); would do, for example).
Do you know how we can log the entire stack trace?