The term ‘logging’ is derived from the action of recording time, speed, and distance in a logbook that was used in ships long before navigational technology was introduced. The logbook would record all problems and monitor various aspects of the ship’s condition.
Table of Contents
Today, the primary intention of logging remains the same, even when used in software technologies.
Logging, in Java, is a great feature that helps developers figure out where an error has originated. It provides them with a Logging API, one of the most helpful features of the Java version 1.4 and lets developers catch the error in the log file.
This blog will help you understand Java logging, the logging levels, logging handlers, appenders, levels, formats, and Java logging classes.
Logging is an API or Application Programming Interface which locates and notifies developers of any errors within a system. When a software faces an error, it generates a logging call stored in the LogRecord and then sent to its corresponding logging handlers and appenders.
Logging handlers record and display logs effectively, either in a console, file, or email. It comprises two critical components, the formatter, which adds context information to a log, and a log level, which acts as a filter to glean out inferior logs.
An appender is responsible for recording the log event to a destination such as your email, electronic device, etc. Appenders are also responsible for formatting the log through a formatter.
If you are wondering why Java logging is important, then the answer is simple. First, it provides all the information needed to trace the error in an application or software.
Second, it records data needed by developers in case there is a critical error in an application.
Three core components are crucial for a Java logging framework and are used to create logs and pass them to their destination using the correct formats. These include:
Java loggers are items that trigger log events. They are created and executed in the application’s code, where they produce Log Events before transferring them to an appender. To respond to different events, you may use numerous loggers in a single class, or you can use Loggers in a set hierarchy.
A more straightforward way to describe this is that they are used to catch logger records and pass them to the appender. Loggers are differentiated using separately named entities, often distinguished by the ‘dot operator’, for example, java.awt or java.net and more.
The LogManager manages the namespace, which is displayed in hierarchical order. It must be consistent with the namespace of the packing. However, it is not necessary to adhere to it perfectly. An anonymous Logger can likewise be created, but it will not show in the shared namespace.
The Logger searches for parent loggers in the logging namespace. It is the nearest ancestor to the current one in the logging namespace. Keep in mind that the root logger has no parent. It inherits different characteristics from its parent, such as:
The Java Logging API enables users to utilize several handlers in a Java logger, with the handlers processing the logs as needed. In Java, there are five logging handlers:
The FileHandler and ConsoleHandler are the two default handlers in the Java Logging API. However, you can design your own and modify the Handler class by extending it or its subclasses such as MemoryHandler, StreamHandler, etc.
The appenders are chosen based on the logging needs. If you are unsure about the appenders to employ, the application’s performance may suffer.
A custom Java Handler can be implemented by the following:
import java.util.logging.LogRecord; import java.util.logging.StreamHandler; public class MyHandler extends StreamHandler { @Override public void publish(LogRecord record) { //add own logic to publish super.publish(record); } @Override public void flush() { super.flush(); } @Override public void close() throws SecurityException { super.close(); } }
Logging formatters, also known as layouts, format log messages and turn data into log events. Java has two standard formatters.
The SimpleFormatter sends out a text message with broad-based information. It generates human-legible log message summaries. The class is used by the ConsoleHandler to print the log information to a device. The following is an example of the message you can expect on your device.
April 28, 2022 11:55:55 PM DemoClass main SEVERE: An exception occurred.
The log message is generated in XML format by the XMLFormatter. It generates a thorough XML structural data. It is the FileHandler’s default formatter. The following are an example of the log entries:
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE log SYSTEM "logger.dtd"> <log> <record> <date>2020-10-29T11:59:55</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>
You can tweak and construct your own Formatter class by extending it. And once constructed, the modified class will prove to be versatile and be used with any handler.
If you’re utilizing logging frameworks, you can choose several styles like HTML, JSON, Syslog, plain text, to name a few. A customized Formatter class may look like this:
import java.util.Date; import java.util.logging.Formatter; import java.util.logging.LogRecord; public class MyFormatter extends Formatter { @Override public String format(LogRecord record) { return record.getThreadID()+"::"+record.getSourceClassName()+"::"+record.getSourceMethodName()+"::"+new Date(record.getMillis())+"::"+record.getMessage()+"n"; } }
Java logging levels indicate the significance and priority of a log message and also govern the logging information. An integer value is assigned to each log level object. The larger the value, the higher the priority.
There are nine levels in all, seven ordinary logs and two unique log levels. The top three logging levels, FINEST, FINER, and FINE, contain extensive tracing data that describes what transpired in the software.
There are two main levels, the Standard Logging and Special Logging levels. These are further divided into:
To configure the logging level, use the following command.
logger.setLevel(Level.CONFIG);
The preceding sentence modifies the logging level automatically to CONFIG, revealing information on the application’s setup.
It also creates a log from the selected level up to the higher levels. If you set the log level to FINE, the resulting log will display CONFIG, INFO, WARNING, and SEVERE.
A class logger in Java is part of the java.util.logging package. It covers all logging-related functions such as:
There is more about Java logging and information available on related elements that can be accessed with the right sources.
For accessing additional resources, follow this link, and unlock more opportunities to develop digital and technological expertise.
At Xperti, we help businesses connect with a large pool of expert engineers and developers to fill your IT and tech positions with the right talent.
Ready to hire? Start here!
Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.
Create a free profile and find your next great opportunity.
Sign up and find a perfect match for your team.
Xperti vets skilled professionals with its unique talent-matching process.
Connect and engage with technology enthusiasts.
© Xperti.io All Rights Reserved
Privacy
Terms of use