In our application, logging is one of the important mechanism to capture the messages thrown by the applications. One of the most popular logging framework is log4j which provides the logging in your applications. However, you can implement the logging without adding any third party implementations by the JDK’s built in logging APIs. java.util.logging package provides the APIs for configuring your application with logging capability.
also read:
A Logger class provided in the java.util.logging package ueed to create a logger object which is used to log messages. A logger object is defined with a name and a set of methods which are used to log messages at the different levels specified in the application.
There are seven logging levels provided by the Level class.
- SEVERE
- WARNING
- INFO
- CONFIG
- FINE
- FINER
- FINEST
The above levels are present in the Level class. Also you have the option to level OFF by stoping any log messages to the printed. Lets look at the very simple example for using the loggers.
JavaLoggerExample.java
package javabeat.net.java.core; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Simple Java Logger example * * @author Krishna * */ public class JavaLoggerExample { private static final Logger LOGGER = Logger.getLogger(JavaLoggerExample.class.getName()); public static void main(String[] args) throws SecurityException, IOException { String str = null; LOGGER.info("Logger Name: "+LOGGER.getName()); LOGGER.warning("Can cause NullPointerException"); try{ System.out.println(str.toString()); }catch(NullPointerException ex){ LOGGER.log(Level.SEVERE, "Exception occur", ex); } } }
Output…
Jun 23, 2014 1:23:46 PM javabeat.net.java.core.JavaLoggerExample main INFO: Logger Name: com.infosys.java.core.JavaLoggerExample Jun 23, 2014 1:23:46 PM com.infosys.java.core.JavaLoggerExample main WARNING: Can cause NullPointerException Jun 23, 2014 1:23:46 PM com.infosys.java.core.JavaLoggerExample main SEVERE: Exception occur java.lang.NullPointerException at javabeat.net.java.core.JavaLoggerExample.main(JavaLoggerExample.java:20)