Java 9 Platform Logging API and Service

Java 9 defines a minimal logging API which platform classes can use to log messages, together with a service interface for consumers of those messages. In this tutorial, we’re gonna take a look at new Java 9 Platform Logging API and an example that implements LoggerFinder service which can route platform log messages to the logging framework for application logger instead of system logger.

I. Platform Logging API and Service

An implementation of LoggerFinder is loaded with help of java.util.ServiceLoader API using system class loader. Basing on this implementation, an application/framework can plug in its own external logging backend, without configuring java.util.logging or that backend.

We can pass the class name or module (related to specific Logger) to the LoggerFinder so that the LoggerFinder can know which logger to return.

If no concrete implementation is found, JDK default LoggerFinder implementation will be used. java.util.logging (in java.logging module) now becomes backend. So log messages will be routed to java.util.logging.Logger.

We obtain loggers that are created from the LoggerFinder using factory methods of the System class:

II. Example

1. Overview

In logger package:
– We will create 2 concrete Loggers that implement Logger interface: MyLogger and MyNewLogger.
MyLoggerFinder is an implementation of LoggerFinder that can return desired Logger by name.
We build logger package into demo.logging module.
This module provides an implementation of LoggerFinder service.

In app packagee, we create a Test Class that uses System factory method getLogger(name) to get Loggers and use them.
We build app package into demo.app module.

Folder tree should be:

2. Practice
2.1 Create implementation of LoggerFinder

2.2 Create implementations of Logger

2.3 Create Module Info file for demo.logging module

2.4 Create a Test Class

2.5 Create Module Info file for demo.app module

2.6 Run and check result

The result is:

III. Source Code

jigsaw-platform-logging


Related Posts



Got Something To Say:

Your email address will not be published. Required fields are marked *

*