Formatter

The Formatter class in java.util.logging is used to control the output format of log messages. When a Logger sends a log record to a Handler, the handler uses a Formatter to convert the LogRecord into a human-readable string.

Common Subclasses of Formatter

Commomly Used Methods

Simple Example with Built-in Formatters

import java.util.logging.*;

public class SimpleFormatterExample {
    public static void main(String[] args) throws Exception {
        Logger logger = Logger.getLogger(SimpleFormatterExample.class.getName());
        logger.setUseParentHandlers(false); // Disable default console output

        FileHandler fh = new FileHandler("simple_log.log");
        
        // Use built-in SimpleFormatter
        fh.setFormatter(new SimpleFormatter());

        logger.addHandler(fh);
        logger.info("Logging with SimpleFormatter");
    }
}
Output in simple_log.log:
May 24, 2025 12:00:00 PM SimpleFormatterExample main
INFO: Logging with SimpleFormatterCode language: CSS (css)

Problem Statement:

LotusJavaPrince and Mahesh need a clean, one-line-per-entry log format for their payment gateway system. The default format adds timestamps and log level on separate lines, which is hard to parse for dashboards. They want a custom formatter that logs messages as:

[LEVEL] – MESSAGE

import java.util.logging.*;
import java.io.IOException;

// Custom Formatter
class OneLineFormatter extends Formatter {
    @Override
    public String format(LogRecord record) {
        return "[" + record.getLevel() + "] - " + record.getMessage() + "\n";
    }
}

class PaymentGateway {
    private static final Logger logger = Logger.getLogger(PaymentGateway.class.getName());

    public void processPayment(String user, double amount) {
        logger.info("Processing payment of $" + amount + " for user: " + user);
        if (amount > 10000) {
            logger.warning("Large payment detected for " + user);
        } else {
            logger.info("Payment processed successfully for " + user);
        }
    }
}

public class PaymentLoggerCaseStudy {
    public static void main(String[] args) {
        try {
            setupCustomFormatter();
        } catch (IOException e) {
            System.err.println("Logger setup failed: " + e.getMessage());
            return;
        }

        PaymentGateway gateway = new PaymentGateway();
        gateway.processPayment("LotusJavaPrince", 5000);  // Normal
        gateway.processPayment("Mahesh", 15000);          // Large
    }

    private static void setupCustomFormatter() throws IOException {
        Logger rootLogger = Logger.getLogger("");
        rootLogger.setUseParentHandlers(false);

        FileHandler fh = new FileHandler("payments.log", true);
        fh.setFormatter(new OneLineFormatter());

        rootLogger.addHandler(fh);
        rootLogger.setLevel(Level.INFO);
    }
}
[INFO] - Processing payment of $5000.0 for user: LotusJavaPrince
[INFO] - Payment processed successfully for LotusJavaPrince
[INFO] - Processing payment of $15000.0 for user: Mahesh
[WARNING] - Large payment detected for Mahesh

Formatter allows full control over how logs are formatted.

  • You can use SimpleFormatter or XMLFormatter, or write your own.
  • Great for creating readable logs, dashboard feeds, or structured outputs.
  • Combine formatters with FileHandler, StreamHandler, or SocketHandler for powerful logging solutions.
Scroll to Top