Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java.util.logging: JDK Comes With A Logging Class

Java provides a built-in logging framework called java.util.logging, which is part of the Java Standard Edition API. This tutorial will guide you through the basics of using java.util.logging to log messages in your Java applications.

  • Import java.util.logging:

First, import the necessary classes from the java.util.logging package.

import java.util.logging.Level;
import java.util.logging.Logger;
  • Get a Logger instance:

To start logging, you need to obtain an instance of the Logger class. The recommended approach is to use the Logger.getLogger() method, passing the name of the class as an argument.

private static final Logger LOGGER = Logger.getLogger(MyClass.class.getName());
  • Log messages:

The Logger class provides several methods to log messages at different levels. The most commonly used levels are:

  • SEVERE: Critical errors that cause the program to terminate.
  • WARNING: Issues that might cause problems but allow the program to continue.
  • INFO: General information about the program's progress.
  • FINE, FINER, FINEST: Detailed debugging information.

Here's an example of logging messages at different levels:

LOGGER.severe("An error occurred");
LOGGER.warning("A potential issue was detected");
LOGGER.info("Application started successfully");
LOGGER.fine("Entering debug mode");
  • Configure the logging level:

By default, the logging level is set to INFO. You can change this by setting the level property on your logger instance.

LOGGER.setLevel(Level.FINE);

Note that the logging level of a logger is also affected by its parent logger and handlers. To configure the logging level globally, you can set the level on the root logger:

Logger.getLogger("").setLevel(Level.FINE);
  • Configure log output:

java.util.logging provides a set of Handler classes for controlling the output of log messages. The most commonly used handlers are:

  • ConsoleHandler: Writes log messages to the console (System.err by default).
  • FileHandler: Writes log messages to a file.
  • StreamHandler: Writes log messages to an OutputStream.

To configure the handlers, you need to add them to your logger instance:

import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Handler;

// ...

FileHandler fileHandler = null;
try {
    fileHandler = new FileHandler("application.log");
} catch (IOException e) {
    LOGGER.log(Level.SEVERE, "Error setting up the file handler", e);
}

if (fileHandler != null) {
    LOGGER.addHandler(fileHandler);
}

ConsoleHandler consoleHandler = new ConsoleHandler();
LOGGER.addHandler(consoleHandler);
  • Customize log format:

By default, log messages are formatted using the SimpleFormatter class. You can change the format by setting a custom Formatter on your handler. For example, to change the format of the console handler:

import java.util.logging.SimpleFormatter;

// ...

SimpleFormatter formatter = new SimpleFormatter() {
    @Override
    public synchronized String format(LogRecord record) {
        return "[" + record.getLevel() + "] "
                + record.getSourceClassName() + ": "
                + record.getMessage() + "\n";
    }
};

consoleHandler.setFormatter(formatter);

This tutorial covered the basics of using the java.util.logging framework in Java, including obtaining a Logger instance, logging messages at different levels, configuring log output, and customizing the log format. Using java.util.logging, you can easily add logging functionality to your Java applications to help with debugging and monitoring.

  1. Logging in Java with java.util.logging

    Java provides a built-in logging framework through java.util.logging.

    import java.util.logging.Logger;
    
    public class LoggingExample {
        private static final Logger LOGGER = Logger.getLogger(LoggingExample.class.getName());
    
        public static void main(String[] args) {
            LOGGER.info("Logging information message");
            LOGGER.warning("Logging warning message");
        }
    }
    
  2. Configuring logging properties in Java

    Configure logging properties using a logging.properties file or programmatically.

    java.util.logging.ConsoleHandler.level = ALL
    
  3. Logging levels in java.util.logging

    Logging levels include SEVERE, WARNING, INFO, CONFIG, FINE, FINER, and FINEST.

    LOGGER.warning("This is a warning message");
    LOGGER.log(Level.INFO, "This is an informational message");
    
  4. Handling loggers and log records in Java

    Customize loggers and process log records.

    Logger logger = Logger.getLogger("com.example");
    logger.addHandler(new CustomHandler());
    
  5. Customizing log formatters in java.util.logging

    Customize log formatting.

    ConsoleHandler consoleHandler = new ConsoleHandler();
    consoleHandler.setFormatter(new CustomFormatter());
    LOGGER.addHandler(consoleHandler);
    
  6. Filtering log messages with Handlers in Java

    Use Handlers to filter log messages.

    FileHandler fileHandler = new FileHandler();
    fileHandler.setFilter(record -> record.getLevel() == Level.WARNING);
    LOGGER.addHandler(fileHandler);
    
  7. Redirecting log output to files in Java

    Redirect log output to files.

    FileHandler fileHandler = new FileHandler("myLogFile.log");
    LOGGER.addHandler(fileHandler);
    
  8. Logging to multiple destinations with java.util.logging

    Log to multiple destinations.

    ConsoleHandler consoleHandler = new ConsoleHandler();
    FileHandler fileHandler = new FileHandler("myLogFile.log");
    
    LOGGER.addHandler(consoleHandler);
    LOGGER.addHandler(fileHandler);