This example shows how to write a simple custom Formatter for the logging in Java. Java provides java.util.Formatter class for extending the format of the messages and that can be applied to the handlers. In our previous example, I have explained how to write the logging handlers.
If you want to write the custom formatters, you have to extend the java.util.Formatter and override the format(LogRecord) with your own implementation. If you look at the example, you can use your own text before and after of the log messages. This formatter will be invoked everytime log messages are printed.
also read:
Lets look at the example.
JavaLoggerFormatterExample.java
package javabeat.net.java.core; import java.io.IOException; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; /** * Simple Java Logger Handler example * * @author Krishna * */ public class JavaLoggerFormatterExample { private static final Logger LOGGER = Logger.getLogger(JavaLoggerFormatterExample.class.getName()); public static void main(String[] args) throws SecurityException, IOException { String str = null; //Creating the log handlers FileHandler fileHandler = new FileHandler("javabeat.log"); fileHandler.setFormatter(new CustomFormatter()); //Add handlers to the logger LOGGER.addHandler(fileHandler); //set the levels for each handler fileHandler.setLevel(Level.ALL); LOGGER.setLevel(Level.ALL); 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); } } }
CustomFormatter.java
package javabeat.net.java.core; import java.util.Date; import java.util.logging.Formatter; import java.util.logging.LogRecord; /** * Example for Custom Formatter * * @author Krishna * */ public class CustomFormatter extends Formatter{ @Override public String format(LogRecord record) { StringBuffer sb = new StringBuffer(); sb.append("\nLogged message on Date "+new Date().getDate() +" : "); sb.append(record.getMessage()); return sb.toString(); } }
Output…
Logged message on Date 23 : Logger Name: javabeat.net.java.core.JavaLoggerFormatterExample Logged message on Date 23 : Can cause NullPointerException Logged message on Date 23 : Exception occur