Java logger
Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted in Java 1.4. The log file can be recorded using this capability. This section will include a thorough analysis of the Java Logger API. We will also talk about the components, the logging handlers or appenders, the logging formatters or layouts, the logging level, the Java Logger class, and the components. It shows how the handlers are handled in the efficient manner and so on, this come across with the covering of every required topic.
What exactly does Java logging?
The Java language has an API called logging that makes it possible to track down programme failures. The event is entered into the LogRecord by the Logger when an application generates the logging call. It then sends to the appropriate handlers or appenders. The appenders format the log record using a formatter or layouts before sending it to the console or file.
Desire for Logging
- It offers the application's full history of tracing information.
- If any critical failures occur while running the application, it notes them.
Logging component
The Java Logging components are used by the developers to produce logs and transmit them in the appropriate format to the desired location. The following three components make up the Java logging API:
- Loggers
- Handlers or Appenders for Logging
- Layouts or Formatters for Logging
Loggers
The Logger objects receive the log request from the client's code and process it. These logger objects maintain a log level that they are interested in and deny requests for logs that are below it.
It is in charge of recording log records, in other words. The records are then sent on to the appropriate appender.
Typically, named entities make up the Loggers objects. objects that are separated by a dot operator. java.net, java.awt, etc. are a few examples.
The namespace is controlled by the LogManager and is organised hierarchically. It must match the packaging namespace in alignment. Although it is not necessary to adhere to it precisely. Although it won't show up in the shared namespace, we can also build an anonymous Logger.
The Logger looks for the parent loggers in the namespace for logging. It is the namespace in logging that is most similar to the current ancestorIt's important to know that the root logger is an orphan. It receives a variety of traits from their parent, including:
- Levels of Logging: If null is supplied, it searches for the top non-null level by moving toward the parent.
- Handlers: Any message sent to the parent's handlers will be logged by a logger, recursively up the tree.
- Names of resource bundles: In the event that a logger's resource bundle name is null, it will recursively up the tree inherit the resource bundle name of any parent.
Handlers or Appenders for Logging
- A Java logger can employ several handlers, and these handlers process the logs appropriately thanks to the Java Logging API. There are five distinct logging handlers available in Java:
- StreamHandler: The prepared log message is written to an OutputStream.
- ConsoleHandler: It outputs to the console all of the prepared log messages.
- Handleroffile: The log message is written in XML format either to a single file or a collection of files that rotate continually.
- SocketHandler: The external TCP ports are used to write the log message.
- MemoryHandler: The buffer log records that are memory-resident are managed by it. The ConsoleHandler and FileHandler are the two standard handlers that are provided by the Java Logging API. The Handler class can be modified and extended by creating new instances of it or any of its subclasses (such as MemoryHandler, StreamHandler, etc.). Depending on the logging requirements, the appenders are chosen. The effectiveness of the application may be impacted if you are unsure which appenders to employ.
Layouts or Formatters for Logging
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
A text message containing broad information is produced by it. It creates log message summaries that are readable by humans. To print the log message to the console, the ConsoleHandler makes use of the class. For instance, the subsequent console message displays
Nov 207, 2022 02:55:55 PM DemoClass main
Server: There was an exception.
XMLFormatter
The log message is created 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="2.0" encoding="UTF-10" standalone="nope"?>
<!DOCTTYPE log SYSTEM "logger.dtd">
<log>
<record>
<Date>2022-12-31T11:59:55</Date>
<millins>1595664378</millins>
<order>0</order>
<logger>DemoClass</logger>
<levels>SEVERE</levels>
<class3>DemoClass</class3>
<method1>main</method1>
<thread2>1</thread2>
<text>An exception has occurred.</text>
</record>
</log>
level We can personalise and construct our own Formatter class by extending the Formatter class. Any handlers can use the modified class.
Other styles, including plain text, Syslog, json, html, etc., can be used if you're using logging frameworks.
Logging Levels of the 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 has an integer value. Higher values correspond to higher priorities. In total, there are nine levels: seven standard log levels and two special log levels. The first three logging levels—FINEST, FINER, and FINE—represent the extensive tracing data, which includes details about what is occurring in the application and what happened in the application. Let's go over each level of logging in more detail.
- 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 programme may have thrown.
- FINE: Out of all of these, it stands for the most significant message.
- CONFIG: It displays data pertaining to the settings of the application. The details could include how much memory and disc space there is.
- INFO: Users' personal data is used by administrators and other authorities.
- WARNING: It occurs due to user mistake. If a user inputs the wrong credentials, the application shows a warning.
- The SEVERE: It happens when the application displays some serious or severe problems. The application is unable to proceed in such circumstances. The database being unavailable and running out of memory are two common examples of a severe level.
Establishing the Logging Level
The logging level can be configured with the following sentence.
logger.setLevel(Level.CONFIG);
In addition to providing information about the application's setup, the aforementioned line also sets the logging level to CONFIG. Additionally, it creates a log that extends from the level that is provided to higher levels.
The output logs would have been CONFIG, INFO, WARNING, and SEVERE if the log level had been set to FINE.
As we've demonstrated below, we can also assign it to the configuration file by simply modifying the Logger's settings:
...
<Loggers>
<Logger naam="HintLogger" level="message">
...
Events of the logging
You must specify a level while logging events in Java in order to categorise them quickly. The following approaches can be used to designate a level and mention a message:
First method
logger.log(Level.Message, "Display the information");
The level Message and information to be printed are both given in the previous sentence.
Second method
logger.data("Display information");
The setLevel() method is used to ensure that only events with a level of INFO or above are logged by the Java logger.
Log Manager for Java
The class java.util.logging contains the LogManager, which is a component of Java. The logger instances are created and maintained, and the global logging settings is tracked. Additionally, we may use it to configure it for our own application-specific needs. These two items are included in it:
- The named 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 initialised. This feature enables container applications (like EJB containers) to override the default LogManager class with their own subclass.
Frameworks for Logging
The logging framework can also be used to simplify the logging notion. The following well-known logging framework is employed for logging:
- Log4j: A Java-based logging tool called Apache Log4j is open-source.
- SLF4J: Simple Logging Facade for Java is what it is called (SLF4J). For several logging frameworks, including Java.util.logging, Log4j, and Logback, it serves as an abstraction layer.
- Logback: Prior to the release of Log4j version 2, it was developed as an open-source project to serve as a successor.