This article describes how to use the Logging API in Java programs. It includes an example for creating a HTML logger.
- LOGGING IN JAVA
The JDK contains the "Java Logging API". Via a logger you can save text to a central place to report on errors, provide additional information about your program, etc. This logging API allows to configure how messages are written by which class with which priority.
- CREATE A LOGGER
The package java.util.logging provides the logging capabilities via the class Logger. To create a logger in your Java coding :
The log levels define the severity of a message. The class Level is used to define which messages should be written to the log. The following lists the Log Levels in descending order :
In addition to that you have also the levels OFF and ALL to turn the logging of or to log everything. For example the following will set the logger to level info which means all messages with severe, warning and info will be logged :
Each logger can have access to several handler. The handler receives the log message from the logger and exports it to a certain target. A handler can be turn off withsetLevel(Level.OFF) and turned on with setLevel(...). You have several standard handler, e.g.
Log Levels INFO and higher will be automatically written to the console.
Each handlers output can be configured with a formatter. Below are Available formatters :
You can also build your own formatter. The following is an example of a formatter which will use create HTML output :
The log manager is responsible for creating and managing the logger and the maintenance of the configuration. We could set the logging level for a package, or even a set of packages, by calling the LogManager.setLevel(String name, Level level) method. So, for example, we could set the logging level of all loggers "logging" to Level.FINE by making this call :
It is common practice to use the fully qualified name of each class whose activity is being logged as a message category because this allows developers to fine-tune log settings for each class. Using the fully qualified class name of your class as the name of your Logger is the approach recommended by the Logging API documentation.
Create your own formatter :
- MyHtmlFormatter.java : Refer to previous FORMATTER example.
Initialize the logger :
- MyLogger.java :
And the txt file :
* 記錄（Logging）: 簡 介 Logging
* 記錄（Logging）: Logging 的層級
* 記錄（Logging）: Handler、 Formatter
* 記錄（Logging）: 自 訂 Formatter
* 記錄（Logging）: 自 訂 Handler
* 記錄（Logging）: 自 訂 Filter
* 記錄（Logging）: Logger 階層關係