August 14, 2022

How to load logging.properties for java.util.logging

In Java Logging APIs or java.util.logging, we use system property java.util.logging.config.file to define the location of the logging.properties file.

Note

Java Logging APIs Tutorial

1. Loads logging.properties at runtime

In the command line, we can use -D option to pass the path of logging.properties via the system property java.util.logging.config.file.

Terminal

$ java -jar -Djava.util.logging.config.file=/path/logging.properties server.jar

$ java -Djava.util.logging.config.file=/path/logging.properties runServer

2. Loads logging.properties from the classpath

Normally, we put the logging.properties at the src/main/resources, and project compile or build will copy it to the root of the classpath. And we can use LogManager or System.setProperty to load the logging.properties programmatically.

2.1 LogManager

The below example uses LogManager to load a logging.properties file from the classpath.

LoadLogPropertiesFile1.java

package com.favtuts;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

public class LoadLogPropertiesFile1 {

  static {
      // must set before the Logger
      // loads logging.properties from the classpath
      try (InputStream is = LoadLogPropertiesFile.class.getClassLoader().
              getResourceAsStream("logging.properties")) {
          LogManager.getLogManager().readConfiguration(is);
      } catch (IOException e) {
          e.printStackTrace();
      }
  }

  private static Logger logger = Logger.getLogger(LoadLogPropertiesFile.class.getName());

  public static void main(String[] args) {

      logger.info("This is level info logging");

  }

}

2.2 System.setProperty(“java.util.logging.config.file”)

The below example uses System.setProperty("java.util.logging.config.file") to load a logging.properties file from the classpath.

LoadLogPropertiesFile2.java

package com.favtuts;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

public class LoadLogPropertiesFile2 {

  static {
      // must set before the Logger
      // loads logging.properties from the classpath
      String path = LoadLogPropertiesFile.class
            .getClassLoader().getResource("logging.properties").getFile();
      System.setProperty("java.util.logging.config.file", path);

  }

  private static Logger logger = Logger.getLogger(LoadLogPropertiesFile.class.getName());

  public static void main(String[] args) {

      logger.info("This is level info logging");

  }

}

3. Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-logging/jul

4. References

Leave a Reply

Your email address will not be published.