- Java print stack trace to log | Logger class
- Example code: Java print stack trace to log
- Logger log methods levels:-
- What is a Java Stack Trace? How to Read & Analyze Traces
- Examples of Java Stack Traces
- Example 1 — Temperature Conversion from Celsius to Fahrenheit
- Example 2 — Function Chaining
- How to Read and Analyze Example 1’s Stack Trace
- How to Fix Example 1’s Code Using Error Handling and Stack Traces
- Examine, Investigate, and Handle Java Errors
- Track, Analyze and Manage Errors With Rollbar
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 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"); > >
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.
What is a Java Stack Trace? How to Read & Analyze Traces
A Java stack trace is displayed when an error or exception occurs. The stack trace, also called a backtrace, consists of a collection of stack records, which store an application’s movement during its execution.
The stack trace includes information about program subroutines and can be used to debug or troubleshoot and is often used to create log files. These exceptions could be custom (defined by the user) or built-in. Examples include RuntimeException , NullPointerException , and ArrayIndexOutofBoundsException .
Now that you know what a stack trace is, let’s take a look at some examples, how to analyze stack traces, and how you can avoid a stack trace altogether with error handling.
Examples of Java Stack Traces
Example 1 — Temperature Conversion from Celsius to Fahrenheit
Let’s look at an example of converting temperatures from Celsius to Fahrenheit. Only an integer or float input is valid here. But if we try to provide another data type, such as a string, the compiler will throw an exception and print the stack trace.
import java.util.Scanner; public class hello < public static void main(String[] args) < Scanner scanner = new Scanner(System.in); System.out.print("Enter value in Celsius to convert in fahrenheit:"); double Celsius = scanner.nextFloat(); double fahrenheit = (Celsius * 1.8)+32; System.out.printf("%.1f degrees Celsuis is %.1f degrees in Fahrenheit ",Celsius,fahrenheit); >>
When we run the above code and enter some invalid value, let’s say the string «hero,» we get the following output:
Enter value in Celsius to convert in fahrenheit: hero Exception in thread "main" java.util.InputMismatchException at java.base/java.util.Scanner.throwFor(Scanner.java:939) at java.base/java.util.Scanner.next(Scanner.java:1594) at java.base/java.util.Scanner.nextFloat(Scanner.java:2496) at com.example.myJavaProject.hello.main(hello.java:12)
Example 2 — Function Chaining
This is an example of function chaining, in which one function calls another in a chain-like fashion. Unlike in Example 1, no exception is thrown here, but the stack trace is explicitly printed using the dumpstack() method (a useful method when creating log files). This is good practice because we can use this code later for maintenance or to check the overall health or condition of the application.
public class Example < public static void main(String args[]) < f1(); >static void f1() < f2(); >static void f2() < f3(); >static void f3() < f4(); >static void f4() < Thread.dumpStack(); >>
When the above code is executed, we get the following output:
java.lang.Exception: Stack trace at java.base/java.lang.Thread.dumpStack(Thread.java:1380) at com.example.myJavaProject.Example.f4(Example.java:25) at com.example.myJavaProject.Example.f3(Example.java:20) at com.example.myJavaProject.Example.f2(Example.java:15) at com.example.myJavaProject.Example.f1(Example.java:10) at com.example.myJavaProject.Example.main(Example.java:6)
How to Read and Analyze Example 1’s Stack Trace
Let’s consider Example 1 for this analysis. Below is the breakdown of the output from its execution:
The first line in the stack trace:
The bottom line in the stack trace:
Now, let’s look at the entire stack trace and try to analyze it:
Enter value in Celsius to convert in fahrenheit: hero Exception in thread "main" java.util.InputMismatchException at java.base/java.util.Scanner.throwFor(Scanner.java:939) at java.base/java.util.Scanner.next(Scanner.java:1594) at java.base/java.util.Scanner.nextFloat(Scanner.java:2496) at com.example.myJavaProject.hello.main(hello.java:12)
The main() method is at the bottom of the stack because that is where the program began. By reading from bottom to top, we can now identify where and what exception is being raised. Tracing the source of this error back to the main() method reveals that an exception occurs when the user’s input is taken.
The second line from the top shows that the float input was taken using the function nextFloat() , which in turn calls the next() function, which in turn calls the throwFor() function. As a result, it throws an InputMismatchException .
How to Fix Example 1’s Code Using Error Handling and Stack Traces
Stack traces and exceptions are clearly related, as evidenced by the preceding examples. Stack traces can be avoided; in short, some common error handling techniques can be used to handle and resolve any exceptions thrown by the code during execution. The technique listed below can help avoid a stack trace.
Examine, Investigate, and Handle Java Errors
It’s common for amateur programmers to overlook exceptions in their code. Being able to examine, investigate, and handle mistakes can be very helpful prior to moving to the next step. Let’s handle the exception in Example 1 by using try and catch statements.
import java.util.Scanner; public class hello < public static void main(String[] args) < Scanner scanner = new Scanner(System.in); System.out.print("Enter value in Celsius to convert in fahrenheit:"); try < double Celsius = scanner.nextFloat(); double fahrenheit = (Celsius * 1.8) + 32; System.out.printf("%.1f degrees Celsuis is %.1f degrees in Fahrenheit ", Celsius, fahrenheit); >catch (InputMismatchException e) < System.out.println("Wrong input type entered. exiting the program"); >> >
In the above code, we have used a try — catch block to catch the exception and then print a custom message to notify the user to enter a valid input.
When the code above is executed, we get the following output:
Enter value in Celsius to convert in fahrenheit: hero
Wrong input type entered. exiting the program
Process finished with exit code 0
With the help of the try and catch blocks, the code to be tested is placed in the try block and any exception thrown by the code is handled in the catch block.
This is the most commonly used method to handle exceptions in Java and thus avoid stack traces.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyse, and manage errors in real-time can help you proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!