Filter

The Filter interface is part of the java.util.logging package and is used to control whether a particular LogRecord should be logged or discarded. Filters can be applied to Logger or Handler objects to fine-tune the logging output.

Commonly Used Methods

Simple Program 

This program logs only messages with level WARNING or above.

import java.util.logging.*;

public class FilterSimpleExample {

    public static void main(String[] args) {
        Logger logger = Logger.getLogger("MyLogger");
        ConsoleHandler handler = new ConsoleHandler();

        // Set custom filter on the handler
        handler.setFilter(new Filter() {
            @Override
            public boolean isLoggable(LogRecord record) {
                // Only log WARNING and above
                return record.getLevel().intValue() >= Level.WARNING.intValue();
            }
        });

        logger.addHandler(handler);
        logger.setUseParentHandlers(false);

        logger.info("This INFO message will NOT be logged");
        logger.warning("This WARNING message will be logged");
        logger.severe("This SEVERE message will be logged");
    }
}

Problem Statement

LotusJavaPrince has developed a Bank Transaction System. Mahesh wants to log only high-value transactions (amount > 10,000) to reduce log clutter and focus on important events.

import java.util.logging.*;

class Transaction {
    private String txnId;
    private double amount;
    private Logger logger;

    public Transaction(String txnId, double amount) {
        this.txnId = txnId;
        this.amount = amount;
        this.logger = Logger.getLogger("TransactionLogger");

        setupLogger();
    }

    private void setupLogger() {
        ConsoleHandler handler = new ConsoleHandler();

        // Filter to log only transactions > 10,000
        handler.setFilter(record -> {
            Object[] params = record.getParameters();
            if (params != null && params.length > 0 && params[0] instanceof Double) {
                double txnAmount = (Double) params[0];
                return txnAmount > 10000;
            }
            return false;
        });

        logger.addHandler(handler);
        logger.setUseParentHandlers(false);
    }

    public void logTransaction() {
        // Pass amount as parameter to log record for filter to inspect
        logger.log(Level.INFO, "Transaction processed: " + txnId + ", Amount: " + amount, new Object[]{amount});
    }
}

public class TransactionFilterCaseStudy {
    public static void main(String[] args) {
        Transaction t1 = new Transaction("TXN1001", 5000);
        t1.logTransaction();  // Won't be logged

        Transaction t2 = new Transaction("TXN1002", 20000);
        t2.logTransaction();  // Will be logged
    }
}

The Filter interface in Java Logging is a powerful way to control which log messages are recorded based on custom criteria. By implementing the isLoggable method, developers can filter logs on levels, message content, parameters, or any attribute of LogRecord.

Using filters effectively helps reduce log noise and focus on important information, which is crucial for large-scale or performance-sensitive applications. Filters are often combined with different handlers and formatters to create a flexible and manageable logging system.

Scroll to Top