How do I set the formatter of logger handlers?

In this example we’ll see how to set the formatter for the logger handlers. We set the formatter by calling the Handler.setFormatter() method. In the code below we set a SimpleFormatter for our FileHandler handler and XMLFormatter for the ConsoleHandler handler.

This SimpleFormatter format the log in a plain text information while on the other side the XMLFormatter format the log record in XML format.

package org.kodejava.util.logging;

import java.util.logging.*;

public class LogFormatter {
    public static void main(String[] args) {
        Logger logger = Logger.getLogger(LogFormatter.class.getName());

        try {
            // Create a FileHandler that will log to mylog.txt with a
            // SimpleFormatter.
            FileHandler simpleHandler = new FileHandler("mylog.txt", true);
            simpleHandler.setFormatter(new SimpleFormatter());

            // Create a ConsoleHandler that will log to the console with
            // an XMLFormatter.
            ConsoleHandler consoleHandler = new ConsoleHandler();
            consoleHandler.setFormatter(new XMLFormatter());

            // Do not send the message to parent handlers.
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Fail to create logger file handler.", e);
        }"Logging application information message.");
        logger.warning("Logging application warning message.");

Leave a Reply

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