How do I compare Logger Level severity?

In this example we see how we can compare the Level severity
between two levels. The Level class has an intValue()
method that return the integer value of Level‘s severity.

package org.kodejava.example.util.logging;

import java.util.logging.Level;

public class LogLevelSeverityCompare {
    public static void main(String[] args) {
        Level info = Level.INFO;
        Level warning = Level.WARNING;
        Level finest = Level.FINEST;

        //
        // To compare the Level severity we compare the intValue of the Level.
        // Each level is assigned a unique integer value as the severity
        // weight of the level.
        //
        if (info.intValue() < warning.intValue()) {
            System.out.println(info + "(" + info.intValue() + ") is less severe than " +
                    warning + "(" + warning.intValue() + ")");
        }

        if (finest.intValue() < info.intValue()) {
            System.out.println(finest + "(" + finest.intValue() + ") is less severe than " +
                    info + "(" + info.intValue()+ ")");
        }
    }
}

When we run the program above will see the following result:

INFO(800) is less severe than WARNING(900)
FINEST(300) is less severe than INFO(800)

How do I get the current Level of a Logger?

Here we demonstrate how to obtain the current level of the Logger
instance. When the level is not set explicitly the level will be inherited from
the parent logger.

package org.kodejava.example.util.logging;

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

public class LoggerGetLevel {
    private static Logger logger = Logger.getLogger(LoggerGetLevel.class.getName());

    public static void main(String[] args) {
        LoggerGetLevel demo = new LoggerGetLevel();
        System.out.println("demo.getLevel(logger) = " + demo.getLevel(logger));

        logger.setLevel(Level.WARNING);
        System.out.println("demo.getLevel(logger) = " + demo.getLevel(logger));
    }

    public Level getLevel(Logger logger) {
        Level level = logger.getLevel();
        if (level == null && logger.getParent() != null) {
            level = logger.getParent().getLevel();
        }
        return level;
    }
}

How do I set the Logger log level?

In this example you see how we can change or set the Logger log
level. The log level will tell the Logger which particular log message
will be logged.

Logger will only record the log message if the level is equal or
higher than the Logger level. For instance when the level set to
Level.SEVERE, no message other than message logged with Logger.severe(String message)
of Logger.log(Level level, String message) will be logged.

package org.kodejava.example.util.logging;

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

public class LogLevelSetting {
    //
    // Obtains a Logger instance, it will create one if it is not already exist.
    //
    private static Logger logger = Logger.getLogger(LogLevelSetting.class.getName());

    public static void main(String[] args) {
        //
        // Set the log level to Level.INFO, the severe message will be logged.
        //
        logger.setLevel(Level.INFO);
        logger.severe("This message will be logged.");

        //
        // Set the log level to Level.SEVERE, the warning message will not be
        // logged as Level.WARNING is smaller than Level.SEVERE
        //
        logger.setLevel(Level.SEVERE);
        logger.warning("This message won't be logged.");

        //
        // Turn of the log, no message will be logged.
        //
        logger.setLevel(Level.OFF);
        logger.info("All log is turned off.");

        //
        // Turn the logger back on, this will result all the corresponding
        // logger message below will be logged.
        //
        logger.setLevel(Level.ALL);
        logger.info("Information message.");
        logger.warning("Warning message.");
        logger.severe("Severe message.");
    }
}

If we run the program above will see the following result displayed:

29 Apr 09 10:06:50 org.kodejava.example.util.logging.LogLevelSetting main
SEVERE: This message will be logged.
29 Apr 09 10:06:50 org.kodejava.example.util.logging.LogLevelSetting main
INFO: Information message.
29 Apr 09 10:06:50 org.kodejava.example.util.logging.LogLevelSetting main
WARNING: Warning message.
29 Apr 09 10:06:50 org.kodejava.example.util.logging.LogLevelSetting main
SEVERE: Severe message.

In the result above we see that the "This message won't be logged."
is not displayed.

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 demo 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.