Smarter Application Logging: Java Logging 101

April 28, 2022
blog pictures 1.1



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.

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.

new java job roles

This blog will help you understand Java logging, the logging levels, logging handlers, appenders, levels, formats, and Java logging classes.

What is Java Logging?

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.

What are the Components of Java Logging?

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:

  • Loggers
  • Logging handlers and appenders
  • Formatters and layouts

Loggers

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:

  • Handlers: A logger will recursively report any note to the parent’s handlers up the tree.
  • Logging Levels: If it is preset to null, it will navigate to the parent log and look for the first non-null level.
  • Resource Bundle Names: If a logger does not have a resource bundle name, it is automatically assigned the resource bundle name of its parent iteratively in the hierarchy.

Appenders and Logging Handlers

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:

  • SocketHandler: It sends log messages to remote TCP ports.
  • FileHandler: It outputs the log message in XML format to a single file or a set of rotating log files.
  • StreamHandler: This component publishes the ready log message to an OutputStream.
  • MemoryHandler: It manages the buffer log records that are stored in memory.
  • ConsoleHandler: This function outputs all formatted log messages to the console.

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.

What Does a Custom Java Handler Look Like?

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();
 }
 }

Formatters and Layouts

Logging formatters, also known as layouts, format log messages and turn data into log events. Java has two standard formatters.

SimpleFormatter

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.

XMLFormatter

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";  

      }  

      }

What are the Java Logging Levels?

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:

  • FINE: It conveys the most vital message of the bunch.
  • FINEST: It denotes the most detailed tracing message.
  • FINER: It contains a detailed tracing message, which covers exceptions raised by the program and method logging data.
  • SEVERE: It develops when the software displays significant mistakes. In certain instances, the application is unable to proceed. A typical example of a severe level is an application running out of memory or database unavailability.
  • WARNING: It arises as a result of a user error. If a user enters incorrect credentials, the software displays a warning.
  • CONFIG: It represents information about the application’s configuration. The information might include how many disc and memory space is available.
  • INFO: The user’s information as utilized by the admin or another authority.

How to Set Up a Logging Level

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.

Java Logging Class

A class logger in Java is part of the java.util.logging package. It covers all logging-related functions such as:

  • It logs messages for a specified application component.
  • Loggers are also assigned a level. If the level shows null, the Logger receives the level from its parent.
  • In the logger namespace, each Logger traces the parent Logger.
  • Logging messages are routed to the registered Handler object. Furthermore, the Handler sends the message to several locations such as files, the operating system, logs, and the console, among others.
  • It is also related to a ResourceBundle name. It’s used to localize a logging message. If it does not have its own ResourceBundle name, it gets the ResourceBundle name from its parent, much as the logging level.
  • The Logger’s methods are all multi-thread safe.

Conclusion

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!

new Java jobs



author

jordan

Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US