Logger class in Java
Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log file is offered. We will explore more into the Java Logger API in this part. We'll also talk about the Java Logger class, the logging level, the components, the logging handlers or appenders, the logger formatters or layouts,
Logger in Java?
Logging is an API in Java that makes it possible to track down program problems. If a logging call is made by an application, the Logger logs that occurrence in the LogRecord. It is then passed to the necessary handlers or appenders. The formatter or layouts are used by the appenders to prepare this log entry before sending it to the console or file.
Needs for logger
- It offers the entire application tracing information.
- The application keeps track of any critical failures that happen.
Elements of logging
Its Java Logging components are used by developers to make logs and deliver these logs in the correct format to the right destination. A Java logging API is made up of the three items listed below:
- Loggers
- Logging handlers or appender
- Logging formatters or layouts
Loggers
The log request is transmitted to the Logger objects by the client's code. These logger objects monitor a log level in which they are interested and refuse log requests that are below it.
In the other words, it's in charge of recording log entries. It then sends these records to the appropriate appender.
The Loggers devices are typically named entities. the things that are divided by the dot operator. java.net, java.awt, etc. are a few examples.
The hierarchy of the namespace, which would be presented, is managed by the LogManager.The alignment must match the packaging namespace. But strict adherence to it is not required. However, it won't appear inside the shared namespace. Another anonymous Logger can also be created.
In the logging namespace, the logger searches for the parent loggers.It is the logging namespace object that is closest to the current ancestor. It receives the following characteristics from its parent:
- Handlers: A logger will log every message passed to a parent's handlers, recursively across the tree.
- Logging tiers: If null is supplied, then top non-null level is sought by progressing toward the parent.
- Resource bundle names: Any logger that contains a null resource bundle name inherits the resource bundle name of any of its parents up the tree recursively.
Logger Handlers or appender
Using several handlers in a Java logger is possible thanks to the Java Logging API, as well as the handlers process the logs appropriately. In Java, there are five different logging handlers:
• StreamHandler: An output stream receives the prepared log message.
• FileHandler: It sends the log text in XML format to a single document or a group of continuously updating log files.
• Socket handler: This feature uses the socket handler to write the log messages to remote TCP ports.
The recollection buffer log records are managed by the MemoryHandler.
The FileHandler & ConsoleHandler are indeed the two default handlers offered by the Java Logging API. By adding new functionality to the Handler class or any of its subclasses, we can create our own custom designs (like MemoryHandler, StreamHandler, etc.). The logging requirements determine which appenders should be used. If you are unsure of which appenders to use, it might affect the program's performance.
Example of a Custom java logging handler:
import java.util.logging.LogRecord;
import java.util.logging.StreamHandler;
public class MyHandler extends StreamHandler
{
@Override
public void publish(LogRecord record)
{
//Publish your own logic
super.publish(record);
}
@Override
public void flush()
{
super.flush();
}
@Override
public void close() throws SecurityException
{
super.close();
}
}
Logging Layouts or Formatters:
The formatters or layouts for logging are used to transform data into log events and format log messages. The two standard formatters classes that Java SE offers are as follows:
- SimpleFormatter
- XMLFormatter
SimpleFormatter:
It generates a text message that contains a lot of information. It produces summaries of log messages that are readable by people. For instance to print a log message to a console, the ConsoleHandler makes use of the class. For instance, the subsequent console message displays.
Nov 15, 2022 07:15:22 PM DemoClass main
SEVERE: An exception occurred.
XMLFormatter
The log message is generated in XML format by the XMLFormatter. It records the specifics of the XML structure. It serves as the FileHandler's default formatter. The log entries appear as follows:
<?xml version= "1.0" encoding= "UTF-8" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
<date>2022-15-29T07:15:22</date>
<millis>1595664378</millis>
<sequence>0</sequence>
<logger>DemoClass</logger>
<level>SEVERE</level>
<class>DemoClass</class>
<method>main</method>
<thread>1</thread>
<message>An exception occurred.</message>
</record>
</log>
We can personalize and develop our own Formatter class simply extending the Formatter class. Any handlers can be used with the modified class.
You can utilize several layouts, including such HTML, JSON, Syslog, plain text, etc. if you're using logging frameworks.
Logger levels in java
It also manages the logging details while providing a general indication of the log message's importance and urgency. Each object at the log level does have an integer value. Higher values correspond to higher priorities. There are a total of nine levels, including 2 distinct log levels and seven standard log levels. The very first 3 logger levels—FINEST, FINER, and Perfectly acceptable the extensive tracing data, which includes details about what is occurring in and what has just happened in the program.
Let's get into more depth about each logger level:
- FINEST: It stands for the extremely thorough tracing message.
- FINER: It stands for the comprehensive tracing message, which records information about the method as well as any exceptions the application may have thrown.
- FINE: Out of all of these, it stands for the most significant message.
- CONFIG: It displays data pertaining to the application's configuration. The details could include the amount of memory and disk space.
- INFO: The operator or other authorities may utilize the user's information.
- WARNING: It happens as a result of user error. The application displays a warning if a user enters incorrect credentials.
- SEVERE: It happens when the application displays some serious or severe problems. In certain conditions, the application cannot be processed. The database being unavailable and running out of memory are two common examples of a severe level.
Configuring the Logger Level:
The logging level can be configured with the following sentence.
The sentence offers information about application setup and set its logging level to CONFIG. Additionally, the log is generated from the given level to higher ones.
If we had the log level set to FINE, the resultant log would have the following values: CONFIG, INFO, WARNING, & SEVERE.
By simply altering the Logger's configuration, you also can set it in the configuration file, as demonstrated below:
..
<Logging>
<Logging name= “DemoLogging” level=”info”>
..
Logger events:
You must specify a level while logging events in Java in order to categorize them quickly. The following approaches can be used to designate a category and mention a message:
Procedure 1:
logger.log(Level.INFO, “Display the message”);
We have provided its level INFO and also the text to be printed as Display message in the aforementioned sentence.
Procedure 2:
logger.info(“Display the message”);
The setLevel() method is used to ensure that the Java logging framework only records messages that seem to be at or above the INFO level.
Log Manager for Java:
The java.util.logging package contains the class known as LogManager in Java. It creates and updates the logger instances as well as keeping track of the overall logging setup. It can also be used to configure itself specifically for a given application. It includes the two items listed below:
- The designated Logger's hierarchical namespace.
- the configuration file is contained in a set of logging control properties.
The getLogManager() method can be used to get the LogManager. With the creation of LogManager, it was automatically initialized. This feature enables container applications (like EJB containers) to override the default LogManager class with their own subclass.
Java New Logger Creation:
Using the getLogger() method, we can simply generate Logger in Java. If a logger has been defined, it detects it and returns it; if not, it sets up a new logger for the named subsystem.
If it establishes a new logger, it will setup the LogManager, as well as the logger's log level, and deliver the output of the logging to its handlers. It'll be stored in the global namespace of LogManager.
Syntax:
public static Logger getLogger(String name)
As a parameter, the logger title is parsed. The offer or data type of the subsystem should be used as the basis for the logger name, which should be divided mostly by dot (.) operator. As an illustration, java.awt, java.net, etc.
If the logger name is not provided then, it generates an appropriate logger and raises NullPointerException.