How to set up java logging using a properties file?

7    Asked by daniel_5133 in Java , Asked on May 7, 2025

How can I set up Java logging using a properties file? Discover the steps to configure Java's built-in logging mechanism with a properties file, allowing you to control log levels, output formats, and destinations without modifying the code.

Answered by Jordan Duncan

Setting up Java logging using a properties file is an efficient way to manage logging configurations, without modifying the code. Here's how you can do it:

1. Create a logging.properties File:

  • Start by creating a logging.properties file in your project’s resources directory (usually src/main/resources in a Maven project).
  • This file will define the logging behavior, including log levels, output format, and destinations.

2. Configure Loggers and Handlers:

In the properties file, you can define loggers and handlers. Here's an example:

# Set the global log level
.level = INFO
# Configure a console handler
java.util.logging.ConsoleHandler.level = ALL
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
# Define a logger
mylogger.level = FINE
mylogger.handlers = java.util.logging.ConsoleHandler

  • java.util.logging.ConsoleHandler handles log output to the console.
  • SimpleFormatter is used to format the log messages in a simple, human-readable format.

3. Configure the Logging in Code:

In your Java code, you’ll need to tell the logging system to use this properties file. You can do this by setting the java.util.logging.config.file system property:

  System.setProperty("java.util.logging.config.file", "path/to/logging.properties");

4. Test the Logging:

Once configured, you can test logging by using Logger in your code:

Logger logger = Logger.getLogger("mylogger");
logger.fine("This is a fine level message");

Why Use a Properties File?

  • Flexibility: You can change logging configurations without modifying the code.
  • Separation of Concerns: Keeps logging configuration separate from your application logic, making it easier to maintain and debug.



Your Answer

Interviews

Parent Categories