logging

Set Formatter for Logger handler

With this example we are going to demonstrate how to set a Formatter for a Logger Handler. The Formatter is used by the Handler to format LogRecords. In short, to set a Formatter for a Logger’s handler you should:

  • Create a new Logger instance with getLogger(String name) API method of Logger.
  • Create a new FileHandler to write to a specific file.
  • Add the handler to the Logger, with addHandler(Handler handler) API method of Logger.
  • Set a Formatter to the Handler, with setFormatter(Formatter newFormatter) API method. In the example we use the SimpleFormatter and the XMLFormatter.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.XMLFormatter;

public class SetFormatterForLoggerHandler {
	
	public static void main(String[] args) throws Exception {
		
		boolean append = false;
	    FileHandler handler = new FileHandler("default.log", append);

	    Logger logger = Logger.getLogger("com.javacodegeeks.snippets.core");
	    logger.addHandler(handler);

	    handler.setFormatter(new SimpleFormatter());
	    logger.info("simple formatter - info message");

	    handler.setFormatter(new XMLFormatter());
	    logger.info("xml formatter - info message");
		
	}

}

Output:

Nov 19, 2011 4:03:15 PM com.javacodegeeks.snippets.core.SetFormatterForLoggerHandler main
INFO: simple formatter - info message
Nov 19, 2011 4:03:15 PM com.javacodegeeks.snippets.core.SetFormatterForLoggerHandler main
INFO: xml formatter - info message

default.log

Nov 19, 2011 4:03:15 PM com.javacodegeeks.snippets.core.SetFormatterForLoggerHandler main
INFO: simple formatter - info message
<record>
  <date>2011-11-19T16:03:15</date>
  <millis>1321711395420</millis>
  <sequence>1</sequence>
  <logger>com.javacodegeeks.snippets.core</logger>
  <level>INFO</level>
  <class>com.javacodegeeks.snippets.core.SetFormatterForLoggerHandler</class>
  <method>main</method>
  <thread>10</thread>
  <message>xml formatter - info message</message>
</record>
</log>

 
This was an example of how to set a Formatter for a Logger Handler in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button