:::: MENU ::::

Java logging API


Java contains a logging API. Let’s see how to use it.

Installation

There is no need to perform any installation because it’s included with the Java JDK.

Configuration

For a basic use the only thing required is to configure the levels of the logger and of the handler and after that to associate both components. By default, the output with the logs will be our IDE console.

Handlers

The handlers are used to specify our log destiny. We can choose a file, the console, etc.

Root Logger

Initially every log use the Root Logger level (the default log). To avoid this we use the reset method of the LogManager component.

Example

package com.luisgomezcaballero.logger_demo;

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

public class Main {
	
	private static final Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

	public static void main(String[] args) {

		LogManager.getLogManager().reset();

		LOGGER.setLevel(Level.CONFIG);

		ConsoleHandler consoleHandler = new ConsoleHandler();
		consoleHandler.setLevel(Level.ALL);
		LOGGER.addHandler(consoleHandler);
		
		LOGGER.log(Level.SEVERE, "Test");
		LOGGER.log(Level.WARNING, "Test");
		LOGGER.log(Level.INFO, "Test");
		LOGGER.log(Level.CONFIG, "Test");
		LOGGER.log(Level.FINE, "Test");
		LOGGER.log(Level.FINER, "Test");
		LOGGER.log(Level.FINEST, "Test");

	}

}

Executing the application (Run as / Java Application) we will se how there only are registered messages of CONFIG level and above.

Repository

A project with a basic example of how to use the Java logging API can be found at https://github.com/luisgomezcaballero/logger-demo.


So, what do you think ?