‘error’ method of Logger interface is used to log an error message and complete error stack trace.
Example
LOGGER.error("Error Occuured while performing division operaiton a: {}, b: {}", a, b, e);
In the above example, last argument ‘e’ is the error thrown by jre. If the last argument in a logging statement is an exception/error, then SLF4J assume that the user wants the last argument to be treated as an exception and not a simple parameter.
Find the below working application.
LogErrorDemo.java
package com.sample.app;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogErrorDemo {
private static final Logger LOGGER = LoggerFactory.getLogger(LogErrorDemo.class);
public static int div(int a, int b) {
return a / b;
}
public static void main(String args[]) {
int a = 10, b = 0;
try {
int e = a / b;
} catch (Exception e) {
LOGGER.error("Error Occuured while performing division operaiton a: {}, b: {}", a, b, e);
}
}
}
Output
ERROR 2021-07-05 14:19:37,843 1 com.sample.app.LogErrorDemo [main] Error Occuured while performing division operaiton a: 10, b: 0 java.lang.ArithmeticException: / by zero at com.sample.app.LogErrorDemo.main(LogErrorDemo.java:17)
You can download complete working application from below link.
https://github.com/harikrishna553/java-libs/blob/master/slf4j/slf4j-miscellaneous/src/main/java/com/sample/app/LogErrorDemo.java
Previous Next Home
No comments:
Post a Comment