Saturday, 17 October 2015

Log4j2: Exceptions logging

Logger class provides throwing, catching methods for effective logging of exceptions.

<T extends Throwable> T throwing(T t)
<T extends Throwable> T throwing(Level level, T t)
Logs an exception to be thrown. The throwing() method can be used by an application when it is throwing an exception that is unlikely to be handled, such as a RuntimeException.

void catching(Throwable t)
void catching(Level level, Throwable t)

Logs an exception or error that has been caught. The catching() method can be used by an application when it catches an Exception that it is not going to rethrow.
package log4j_tutorial;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class HelloWorld {
 private static final Logger logger = LogManager.getLogger();

 public static String helloMessage(String name) {

  if (name == null) {
   logger.throwing(Level.ERROR, new NullPointerException(
     "name shouldn't be null"));
  }

  return logger.exit(name);
 }

 public static void main(String args[]) {

  try {
   helloMessage(null);
  } catch (NullPointerException e) {
   logger.catching(e);
  }

  helloMessage("Hari Krishna");
 }
}


Output
10:17:56.759 [main] ERROR log4j_tutorial.HelloWorld - throwing
java.lang.NullPointerException: name shouldn't be null
 at log4j_tutorial.HelloWorld.helloMessage(HelloWorld.java:14) [classes/:?]
 at log4j_tutorial.HelloWorld.main(HelloWorld.java:23) [classes/:?]
10:17:56.763 [main] TRACE log4j_tutorial.HelloWorld - exit
10:17:56.763 [main] TRACE log4j_tutorial.HelloWorld - exit with(Hari Krishna)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment