English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
The following diagram shows the core components and specified process of the Java Logging API (java.util.logging).
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 |
---|---|
SEVERE | Serious failure |
WARNING | Warning messages, potential issues |
INFO | Routine runtime information |
CONFIG | Configuration 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.
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.
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();
The log handler or plugin will receiveLogRecordand export it to various targets.
Java SE provides5built-in handlers:
handlers | Use |
---|---|
StreamHandler | write to OutputStream |
ConsoleHandler | write to the console |
FileHandler | write to a file |
SocketHandler | write to a remote TCP port |
MemoryHandler | write 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();
The handler can also useFormatterprocessLogRecordobjectsformattingfor strings, and then export them to external systems.
Java SE has two built-inFormatter:
Formatter | Use |
---|---|
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());
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();
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