How do I set a filter on a logger handler?

This example give you an example on how to set the Filter of a logger handler. In the code below we implements the Filter on the FileHandler to log only a Level.SEVERE message. Other level log will not recorded to the file.

package org.kodejava.example.util.logging;

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

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

        FileHandler handler = null;
        try {
            handler = new FileHandler("myapp.log");
            handler.setFilter(new Filter() {
                public boolean isLoggable(LogRecord record) {
                    // When the LogRecord level is equals to Level.SEVERE the 
                    // message is recorded to the file.
                    return record.getLevel().equals(Level.SEVERE);
                }
            });
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Fail to create logger handler", e);
        }

        logger.addHandler(handler);

        logger.info("Information message");
        logger.warning("Warning message");
        logger.severe("Severe message");
    }
}

How do I use Logger’s MemoryHandler class?

In this example we demonstrate the use of Logger‘s MemoryHandler to log only when some conditions happen in our application, for example when a Level.SEVERE message is logged.

We create an instance of MemoryHandler that will delegate the log to FileHandler class and it logs the last 100 record until a Level.SEVERE message is logged.

package org.kodejava.example.util.logging;

import java.util.logging.Logger;
import java.util.logging.FileHandler;
import java.util.logging.MemoryHandler;
import java.util.logging.Level;

public class MemoryHandlerDemo {
    public static void main(String[] args) {
        MemoryHandlerDemo demo = new MemoryHandlerDemo();
        try {
            demo.testMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void testMethod() throws Exception {
        Logger logger = Logger.getLogger(MemoryHandlerDemo.class.getName());
        FileHandler fileHandler = new FileHandler("myapp.log");

        // Create a MemoryHandler that will dump the log messages for the 
        // latest 100 records when a Level.SEVERE log is logged to by the
        // Logger class.
        MemoryHandler memoryHandler = new MemoryHandler(fileHandler, 100, Level.SEVERE);
        logger.addHandler(memoryHandler);

        // Write some messages to the log
        logger.info("Information message");
        logger.warning("Warning message");

    // This causes the log messages dump to the file log.
        logger.severe("Severe message");
    }
}

To check if the message is logged you can open the myapp.log file created by this small program.

How do I use logger ConsoleHandler?

In this example you’ll see how to add ConsoleHandler to the Logger instance. It is simple, just create an instance of ConsoleHandler and add it to the Logger using the Logger.addHandler() method.

package org.kodejava.example.util.logging;

import java.util.logging.Logger;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;

public class LogConsoleHandler {
    public static void main(String[] args) {
        // Obtains Logger instance
        Logger logger = Logger.getLogger(LogConsoleHandler.class.getName());

        // Add ConsoleHandler to Logger.
        ConsoleHandler consoleHandler = new ConsoleHandler();
        logger.addHandler(consoleHandler);

        if (logger.isLoggable(Level.INFO)) {
            logger.info("This is information message for testing ConsoleHandler");
        }
    }
}

How do I write log to a file?

An application log need to be persisted so that we can analyzed the log when an error occurred in our application. For this reason we need to write to log into a file.

The Logging API provide handlers which helps us to do this. To write log to a file we can use the FileHandler. We define the name of our log file and the appendable mode in this class constructor. For example you can look at the code presented below.

package org.kodejava.example.util.logging;

import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.io.IOException;

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

        // Create an instance of FileHandler that write log to a file called
        // app.log. Each new message will be appended at the at of the log file.
        FileHandler fileHandler = new FileHandler("app.log", true);        
        logger.addHandler(fileHandler);

        if (logger.isLoggable(Level.INFO)) {
            logger.info("Information message");
        }

        if (logger.isLoggable(Level.WARNING)) {
            logger.warning("Warning message");
        }

    }
}