Javatpoint Logo
Javatpoint Logo

Java Logger

In Java, logging is an important feature that helps developers to trace out the errors. Java is the programming language that comes with the logging approach. It provides a Logging API that was introduced in Java 1.4 version. It provides the ability to capture the log file. In this section, we are going to deep dive into the Java Logger API. Also, we will cover logging level, components, Logging handlers or appenders, logging formatters or layouts, Java Logger class,

What is logging in Java?

In Java, Logging is an API that provides the ability to trace out the errors of the applications. When an application generates the logging call, the Logger records the event in the LogRecord. After that, it sends to the corresponding handlers or appenders. Before sending it to the console or file, the appenders format that log record by using the formatter or layouts.

Need for Logging

  • It provides the complete tracing information of the application.
  • It records the critical failure if any occur in an application.

Components of Logging

The Java Logging components used by the developers to create logs and passes these logs to the corresponding destination in the proper format. There are the following three core components of the Java logging API:

  • Loggers
  • Logging Handlers or Appender
  • Logging Formatters or Layouts

Loggers

The code used by the client sends the log request to the Logger objects. These logger objects keep track of a log level that is interested in, also rejects the log requests that are below this level.

In other words, it is responsible for capturing log records. After that, it passes the records to the corresponding appender.

Generally, the Loggers objects are named entities. The entities separated by the dot operator. For example, java.net, java.awt, etc.

The namespace is managed by the LogManager and it is represented in hierarchical order. It must be aligned with the packaging namespace. But it is not mandatory to follow it exactly. We can also create an anonymous Logger but it will not appear in the shared namespace.

In the logging namespace, the Logger search for the parent loggers. It is closest to the extant ancestor in the logging namespace. Remember that there is no parent for the root logger. It inherits the various attributes from their parent such as:

  • Logging Levels: If it is specified to null, it traverses towards the parent and search for the first non-null level.
  • Handlers: a logger will log any message to the handlers of the parent recursively up to the tree.
  • Resource bundle names: If any logger has a null resource bundle name, it inherits any resource bundle name for its parent recursively up to the tree.

Logging Handlers or Appender

Java Logging API allows us to use multiple handlers in a Java logger and the handlers process the logs accordingly. There are the five logging handlers in Java:

  • StreamHandler: It writes the formatted log message to an OutputStream.
  • ConsoleHandler: It writes all the formatted log messages to the console.
  • FileHandler: It writes the log message either to a single file or a group of rotating log files in the XML format.
  • SocketHandler: It writes the log message to the remote TCP ports.
  • MemoryHandler: It handles the buffer log records resides in the memory.

In the Java Logging API, the FileHandler and ConsoleHandler are the two handlers provided by default. By extending the Handler class or any subclasses (like MemoryHandler, StreamHandler, etc.), we can create our own and also customize the Handler class. the selection of the appenders depends on the logging requirements. If you are not sure which appenders to use, it may affect the application's performance.

Example of Custom Java Logging Handler

Logging Formatters or Layouts

The logging formatters or layouts are used to format the log messages and convert data into log events. Java SE provides the following two standard formatters class:

  • SimpleFormatter
  • XMLFormatter

SimpleFormatter

It generates a text message that has general information. It writes human-readable summaries of log messages. The ConsoleHandler uses the class to print the log message to the console. For example, the following console message shows

XMLFormatter

The XMLFormatter generates the log message in XML format. It writes the detailed XML structure information. It is the default formatter for the FileHandler. The log entries look like the following:

By extending the Formatter class, we can customize and create our own Formatter class. We can use the customized class with any handlers.

If you are using Logging frameworks, you can use other layouts such as HTML, JSON, Syslog, plain text, etc.

Example of Customized Formatter Class

Java Logging Levels

It shows the rough guide to the importance and urgency of the log message, and also controls the logging details. Each log level object has an integer value. The higher value indicates higher priorities. There is a total of nine levels, seven standard logs, and two special log levels. The first three logging levels FINEST, FINER, and FINE represent the detailed tracing information that includes what is going on in the application and what happened in the application.

Java Logger

The following table shows the level and the value corresponding to it.

S. No. Standard Log Levels Level Value Used For
1 FINEST 300 Specialized Developer Information
2 FINER 400 Detailed Developer Information
3 FINE 500 General Developer Information
4 CONFIG 700 Configuration Information
5 INFO 800 General Information
6 WARNING 900 Potential Problem
7 SEVERE 1000 Represents serious failure
8 Special Log Levels OFF Integer.MAX_VALUE Turns off the logging
9 ALL Integer.MIN_VALUE Captures everything

Let's discuss each logging level in detail.

  • FINEST: It represents the highly detailed tracing message.
  • FINER: It represents the detailed tracing message that includes exceptions thrown by the application, logging details of the method.
  • FINE: It represents the most important message out of these.
  • CONFIG: It represents the information related to the configuration of the application. The information may include how much the disk and memory space.
  • INFO: The information of the user used by the administrator or other authorities.
  • WARNING: It occurs due to user mistake. If a user inputs the wrong credentials, the application shows a warning.
  • SEVERE: It occurs when some critical or terrible errors shown by the application. In such cases, the application is not able to continue further. The popular example of a severe level is out of memory and unavailability of the database.

Setting Up the Logging Level

We can use the following statement to set up the logging level.

The above statement sets the logging level to CONFIG and provides the information related to the configuration of the application. It also generates the log from the specified level to the greater levels.

Suppose, we have specified the log level to FINE, then the generated log will be CONFIG, INFO, WARNING, and SEVERE.

We can also set it to the configuration file just by changing the Logger's configuration, as we have shown below:

Logging Events

To log events in Java, you have to make sure that you assign a level to easily filer out the events. To assign a level and mention a message we can use the methods given below:

Method 1:

In the above statement, we have specified the level INFO and the message to be printed is, Display message.

Method 2:

Logger in Java logs only events that are at or above the INFO level, to make sure this, we use the setLevel() method.

Java Log Manager

In Java, the LogManager is a class that belongs to the java.util.logging package. It keeps track the global logging configuration, creates, and maintains the logger instances. We can also use it to set its own application-specific configuration. It includes the following two things:

  • The hierarchical namespace of named Logger.
  • A group of logging control properties that contains the configuration file.

The LogManager can be retrieved by using the getLogManager() method. It automatically initialized when we create LogManager. This property allows container applications (such as EJB containers) to substitute their own subclass of LogManager in place of the default class.

Create New Logger in Java

We can easily create Logger in Java by using the getLogger() method. It finds a logger if a logger is already defined and returns the same logger, else creates a new logger for a named subsystem.

If it creates a new logger, its log level will be configured that depend on the LogManager configuration, also configures the LogManager, and sends the logging output to its Handlers. It will be registered in the LogManager global namespace.

Syntax:

It parses the logger name as a parameter. The logger name must be separated by the dot (.) operator and should be based on the package name or class name of the subsystem. For example, java.awt, java.net, etc.

It returns a suitable logger and throws NullPointerException if we do not specify the logger name.

Example:

Java Logger Class

Java provides a class Logger that belongs to java.util.logging package. It contains the methods related to logging.

  • It is used to log messages for a specific application component.
  • Each Logger track the parent Logger (nearest existing ancestor) in the logger namespace.
  • Loggers also have an associated level. If the level is null, it inherits the level from its parent Logger.
  • It also has a ResourceBundle name associated with it. It is used for localizing logging messages. Like the logging level, if it does not have its own ResourceBundle name then it inherits the ResourceBundle name from its parent.
  • The logging messages forward to the Handler object that is registered. Further, the Handler forwards the message to a variety of destinations such as files, OS, logs, and console, etc.
  • All the methods of the Logger are multi-thread safe.

The logger class provides methods for logging that are grouped into the following five categories:

  • It provides a group of log The method takes a log level, a message, and some optional parameters for the message.
  • There is another set of methods called the logp It is the same as the log method but also takes the class name and method name, explicitly.
  • It provides another group of methods called logrb (log that includes resource bundle). It is similar to the logp methods but also takes the resource bundle name, explicitly that localize the log message.
  • The class also provides a group of methods that trace the method entries is known as entering
  • It also provides methods for tracing the method entries, such as a method that throws an exception is grouped into throwing exceptions. Similarly, a method that returns something is grouped into existing methods.
  • Also contains a set of convenience methods that are used in the simplest methods. It is used if the programmer simply wants to log a string at the specified level. These methods take a message string as an argument.

Therefore, we can conclude that the LogManager performs the actual logging. The instances of the LogManager accessed by the getLogger() method. The global logger instance is retrieved by the static field GLOBAL_LOGGER_NAME of the Logger class. It provides casual use of the Logging package.

Logging Frameworks

We can also use the logging framework to make the logging concept easy. There is the following popular logging framework used for logging:

  • Log4j: Apache Log4j is an open-source Java-based logging utility.
  • SLF4J: It stands for Simple Logging Facade for Java (SLF4J). It is an abstraction layer for multiple logging frameworks such as Log4j, Logback, and java.util.logging.
  • Logback: It is an open-source project designed as a successor to Log4j version 1 before Log4j version 2 was released.
  • tinylog(tinylog): It is a light weighted and open-source logger.





Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA