FileHandler

The FileHandler in java.util.logging is used to write log messages to disk files. It supports features like log rotation and appending to existing files.

Key Features

  • Writes logs to files.
  • Can rotate log files based on size and limit.
  • Can append to existing files.
  • Works with formatters like SimpleFormatter or custom ones.

Commonly Used Methods

Simple Program

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

public class SimpleFileHandlerDemo {
    public static void main(String[] args) {
        Logger logger = Logger.getLogger("file.logger");
        logger.setUseParentHandlers(false);

        try {
            FileHandler fileHandler = new FileHandler("simplelog.log", true); // append = true
            fileHandler.setLevel(Level.ALL);
            fileHandler.setFormatter(new SimpleFormatter());

            logger.addHandler(fileHandler);
            logger.setLevel(Level.ALL);

            logger.info("This is an INFO log to file.");
            logger.warning("This is a WARNING log to file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output: simplelog.log contains:

May 24, 2025 10:45:00 AM SimpleFileHandlerDemo main
INFO: This is an INFO log to file.
May 24, 2025 10:45:00 AM SimpleFileHandlerDemo main
WARNING: This is a WARNING log to file.Code language: CSS (css)

Problem Statement

LotusJavaPrince and Mahesh are developing a secure transaction system. Logs should not go to the console. Instead, they must go to a rotating log file system to track transactions and errors while ensuring file size is controlled.

They use FileHandler with log rotation and a custom formatter for readable output.

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

class TransactionFormatter extends Formatter {
    public String format(LogRecord record) {
        return String.format("[%s] - %s: %s%n",
            record.getLevel(),
            record.getLoggerName(),
            record.getMessage());
    }
}

public class TransactionLogger {
    private static final Logger logger = Logger.getLogger("com.bank.transaction");

    public static void main(String[] args) {
        setupLogger();

        processTransaction("LotusJavaPrince", 10000, true);
        processTransaction("Mahesh", 25000, false);
        processTransaction("Intruder", 50000, false);
    }

    private static void setupLogger() {
        logger.setUseParentHandlers(false);

        try {
            // Limit = 1MB, Count = 5 rotating files
            FileHandler fh = new FileHandler("transactions.log", 1024 * 1024, 5, true);
            fh.setFormatter(new TransactionFormatter());
            fh.setLevel(Level.INFO);

            logger.addHandler(fh);
            logger.setLevel(Level.ALL);

        } catch (IOException e) {
            System.err.println("FileHandler setup failed: " + e.getMessage());
        }
    }

    private static void processTransaction(String user, double amount, boolean success) {
        if (success) {
            logger.info(user + " transferred $" + amount + " successfully.");
        } else if ("Mahesh".equals(user)) {
            logger.warning("Transaction failed for Mahesh. Exceeds daily limit.");
        } else {
            logger.severe("Unauthorized transaction attempt by " + user + "!");
        }
    }
}

Output: transactions.log (rotated if size > 1MB)

[INFO] - com.bank.transaction: LotusJavaPrince transferred $10000.0 successfully.
[WARNING] - com.bank.transaction: Transaction failed for Mahesh. Exceeds daily limit.
[SEVERE] - com.bank.transaction: Unauthorized transaction attempt by Intruder!

FileHandler play a vital role in directing log messages to their respective file.

  • Ideal for production-grade logging.
  • Saves logs to a file on disk.
  • Supports log rotation, file size limits, and appending.
  • Useful for audit trails, security tracking, and error diagnostics.
Scroll to Top