English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input/Output (I/O)

Java Reader/Writer

Other Java Topics

Java Logging (Logging)

In this tutorial, we will learn Java logging and its various components through examples.

Java allows us to create and capture log messages and files through the logging process.

In Java, logging requires frameworks and APIs. Java has an integrated logging framework in the java.util.logging package.

We can also use third-party frameworks (such as Log4j, Logback, etc.) are used for logging.

Java log components

The following diagram shows the core components and specified process of the Java Logging API (java.util.logging).

Java logging flowchart

1.Logger

The Logger class provides logging methods. We can instantiate an object from the Logger class and call its methods to log.

Let's take an example.

Logger logger = Logger.getLogger("newLoggerName");

The getLogger() method of the Logger class is used to find or create a new Logger. The string parameter defines the name of the logger.

Here, this will create a new Logger object or return a Logger object with the same name.

By convention, a Logger is defined after the class.getName() in the current class.

Logger logger = Logger.getLogger(MyClass.class.getName());

Note:If the passed name is null, this method will throw a NullPointerException.

Each Logger has a level that determines the importance of log messages. There are7A basic log level:

Log levels (in descending order)Use
SEVERESerious failure
WARNING

Warning messages, potential issues

INFORoutine runtime information
CONFIGConfiguration information
FINE

Standard developer information (trace messages)

FINER

Detailed developer information (trace messages)

FINEST

Highly detailed developer information (trace messages)

OFF

Close logging for all levels (do not capture any content)

ALL

Open logging for all levels (capture all content)

Each log level has an integer value that determines its severity, except for the two special log levels OFF and ALL.

Log message

By default, the first three log levels are always logged. To set other levels, we can use the following code:

logger.setLevel(Level.LogLevel);
// Example
logger.setLevel(Level.FINE);

In this example, only Level.FINE and above levels are set for logging. All other log messages are to be deleted.

Now we need to log a log message, and we use the log() method for that.

logger.log(Level.LogLevel, "log message");
// Example
logger.log(Level.INFO, "This is an INFO log level message");

There are some shorthand methods for recording the required level.

logger.info("This is an INFO log level message");
logger.warning("This is a WARNING log level message");

Then, all log requests that have passed through the set log level will be forwarded toLogRecord.

Note:If a logger's level is set to null, then its level will be inherited from its parent, and so on.

2.Filter (Filter)

the filter (if it exists) decides whether to forward the LogRecord, as the name implies, it filters log messages based on specific standards.

IfLogRecordIf the specified conditions are met, only the records from the logger are passed to the log handler, and from the log handler to the external system.

// logger.setFilter(filter);
Set filter
// Get filter
Filter filter = logger.getFilter();

3.handler (output source)

The log handler or plugin will receiveLogRecordand export it to various targets.

Java SE provides5built-in handlers:

handlersUse
StreamHandler

write to OutputStream

ConsoleHandlerwrite to the console
FileHandlerwrite to a file
SocketHandler

write to a remote TCP port

MemoryHandlerwrite to memory

Handlers canLogRecordpass it to the filter to determine again whether it can be forwarded to the external system.

To add a new handler, we use the following code:

logger.addHandler(handler);
// Example
Handler handler = new ConsoleHandler();
logger.addHandler(handler);

To remove a handler, we use the following code:

logger.removeHandler(handler);
// Example
Handler handler = new ConsoleHandler();
logger.addHandler(handler);
logger.removeHandler(handler);

A logger can have multiple handlers. To get all handlers, we use the following code:

Handler[] handlers = logger.getHandlers();

4.formatter (Formatter)

The handler can also useFormatterprocessLogRecordobjectsformattingfor strings, and then export them to external systems.

Java SE has two built-inFormatter:

FormatterUse
SimpleFormatter

Format LogRecord as string

XMLFormatter

Format LogRecord as XML format

We can use the following code to format the handler:

// Formatted into string form
handler.setFormatter(new SimpleFormatter());
// Formatted into XML format
handler.setFormatter(new XMLFormatter());

Logger Manager

Logging ManagementIt is a global record of information about object tracking. It reads and maintains the logging configuration and logger instances.

The logger manager is a singleton, which means only one instance is instantiated.

To obtain the instance of the logger manager, we use the following code:

LogManager manager = new LogManager();

Advantages of Logging

Here are some advantages of using Java logging.

  • Help monitor the flow of the program

  • Help capture any errors that may occur

  • Provide support for problem diagnosis and debugging