Create Custom Formatter for Logger Handler

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.


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

		//set the levels for each handler
		LOGGER.setLevel(Level.ALL);"Logger Name: "+LOGGER.getName());
		LOGGER.warning("Can cause NullPointerException");
		}catch(NullPointerException ex){
			LOGGER.log(Level.SEVERE, "Exception occur", ex);


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{
	public String format(LogRecord record) {
		StringBuffer sb = new StringBuffer();
		sb.append("\nLogged message on Date "+new Date().getDate() +" : ");
		return sb.toString();


Logged message on Date 23 : Logger Name:
Logged message on Date 23 : Can cause NullPointerException
Logged message on Date 23 : Exception occur

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!