This demo shows how the java.util.logging.*
API can be used with Native Image. If your application requires additional logging handlers, you can register them with a custom configuration file, logging.properties, and initialize at build time. This reduces the size of the resulting executable file and improves startup time. Unless your application needs to process logging.properties at run time, this approach is recommended. Both approaches are demonstrated in the examples.
-
Download and install the latest GraalVM JDK using SDKMAN!.
sdk install java 21.0.1-graal
-
Download or clone the repository and navigate into the
native-image-logging-examples
directory:git clone https://github.com/graalvm/graalvm-demos
cd graalvm-demos/native-image-logging-examples
There are two Java classes: one for the build-time logger initialization and the second for run-time logger initialization. The logger will be initialized with a custom logging.properties configuration file, which is placed in the same directory as LoggerBuildTimeInit.java and LoggerRunTimeInit.java.
In this example, the logger will be initialized at build time with a custom logging.properties configuration file, placed in the same repository as LoggerBuildTimeInit.java.
-
Compile LoggerBuildTimeInit.java using
javac
:$JAVA_HOME/bin/javac LoggerBuildTimeInit.java
-
Build and run the native executable:
$JAVA_HOME/bin/native-image LoggerBuildTimeInit --initialize-at-build-time=LoggerBuildTimeInit
./loggerbuildtimeinit
It should produce the output that looks similar to:
WARNING: Danger, Will Robinson! [Thu Dec 14 10:33:06 EET 2023]
The logging.properties file is processed when the executable is built. LoggerHolder.LOGGER
is initialized at build time and is available at runtime, therefore improving the startup time. Unless your application needs to process a custom logging.properties configuration file at runtime, this approach is recommended.
The logger can also be initialized at runtime.
-
Compile LoggerRunTimeInit.java using
javac
:$JAVA_HOME/bin/javac LoggerRunTimeInit.java
-
Build and run the native executable:
$JAVA_HOME/bin/native-image LoggerRunTimeInit -H:IncludeResources="logging.properties"
./loggerruntimeinit
It should produce the output that looks similar to:
WARNING: Danger, Will Robinson! [Thu Dec 14 10:38:30 EET 2023]
In this case, the logging.properties file needs to be available for runtime processing and it must be included in the executable via the
-H:IncludeResources=logging.properties
option. For more details, see Use of Resources in a Native Executable.
Native Image supports logging using the java.util.logging.*
API.
The logging configuration by default is based on the logging.properties file found in the JDK.