Logger in Java

Logging is an important feature to trace out the error. The logger messages are very significant in providing details about what is happening in the application. Writing the logger messages without affecting the application's performance is important. We might wonder why we are using logger instead of Sysout. The reason for using a logger is given below.

  • One of the concerns with Sysout is that log messages are only printed on the console. So, all the logs will be lost once we close the console. Logger messages can be saved to different destinations using Appender.
  • Logger messages can be configured at higher or lower granularity using different logging frameworks. If we want to display the warning level log messages only, we can configure that during the run time.
  • It can include information such as the class, line number, and the date and time of the message.
  • Through the logging frameworks, we can turn on or off the logging at runtime by changing the configuration file.
  • Loggers are optimized for speed compared to Sysout. The Sysout is an IO operation; the IO operation consumes performance.

The Java logging components help the developers in creating logs, passing the logs to the respective destination and maintaining a proper format. The logging components are described below.

Logging Components

Logger

The logger is responsible for capturing log records and passing them to the corresponding Appender. They allow developers to add log statements to their code and define the severity level of each message. The syntax for creating a logger is given below.

Logger logger = Logger.getLogger(SampleClass.class.getName());

Logging levels are used to organize the entries in the log file. It is a simple and efficient way of differentiating log events from each other. If the log levels are used appropriately in the application, all we need is to look at the severity. Here, we presented each of the log levels in a simple way.

TRACE

The trace logging level is used in scenarios where we need full visibility of what is occurring inside the application and the third-party libraries we utilize. We can use it to annotate each query with parameters in the code. We can expect the TRACE logging level to be very lengthy.

DEBUG

DEBUG level is helpful to ensure everything is working fine while running the application in the test environment. It is less granular compared to the TRACE logging level. If we need the details for diagnosing issues and troubleshooting, we can use DEBUG log level.

INFO

INFO is the standard log level indicating that something happened in the application. For example, a controller of your login API may include an INFO log level with information on which user tries to log in to the application and whether the login is successful. The information logged using the INFO log level will be purely informative.to monitor the INFO level messages regularly because it will not result in missing any important information.

WARN

This log level indicates that something unexpected occurred in the application that might disturb one of the methodologies. But that doesn’t indicate that the application failed. The WARN level can be used in unexpected situations, but the code can continue the job even after the exception. For example, if we have a feature to upload a file that fails due to some error in the system, we can indicate that error using WARN level.

ERROR

The ERROR log level is used to indicate a severe problem that you must have to scrutinize immediately. It simply means that your application has met a really undesired state. For example, if one of the payment options is unavailable and we still have the checkout option in our cart.

FATAL

The FATAL log level, like ERROR, represents a problem. But unlike ERROR, it means a severe error occurrence. It indicates that the application entered a condition where one of the necessary business functionality is no longer functioning. For example, suppose the application cannot connect to the database, or all payment systems are unavailable. In that case, users can't check out from their cart.

Filters

Filter is a component that decides whether the LogRecord should be forwarded to the output. It provides a way to fine-tune the logging behavior based on specific criteria.
Filters examine each log record and determine whether it should be included in the logging output. They can be applied at different levels, such as the logger, handler, or formatter.

Below given example illustrates a filter. It is a threshold filter to remove all logger levels below ERROR level.

<Filters>
	<ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>

Appenders or Handlers

Appenders (Appenders are also called Handlers in some logging frameworks) are responsible for recording log events to a destination. Appenders use Layouts to format events before sending them to an output.

Some of the appender implementation classes are FileAppender, ConsoleAppender, JDBCAppender, SMTPAppender, SocketAppender, SyslogAppender, TelnetAppender, and WriterAppender.

FileAppender

It writes the log message to a single or a group of rotating log files in an XML format.

ConsoleAppender

It writes all the log messages to the console.

JDBCAppender

It writes log messages to the database using Java Database Connectivity(JDBC)

SMTPAppender

This appender sends log messages as emails using the Simple Mail Transfer Protocol (SMTP).

SocketAppender

SocketAppender writes the log message to remote TCP ports.

SyslogAppender

SyslogAppender Sends log messages to a Syslog server. Syslog is a standard protocol for logging in the Unix/Linux environments.

TelnetAppender

It is a log4j appender that writes the log messages to a read-only socket. The output is delivered in a telnet-friendly way so that the log can be monitored over TCP/IP. Clients using telnet can receive log data.

WriterAppender

Depending on the user's choice, it appends log events to a Writer or an OutputStream.

StreamAppender

It writes the log message to an output stream.

MemoryAppender

It handles the buffer log records that reside in the memory.

The following code snippet shows a sample snippet of an appender in the xml file.

<Appenders>
	<Console name="console" target="SYSTEM_OUT">
	  <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level    
	  %logger{36} - %msg%n" />
	</Console>
</Appenders>

Formatters or Layouts

Layout objects are used to format the logging information in different styles. It plays an important role in publishing logging information in a human-readable form.

The layout can be defined as below. This is a pattern layout and it defines the pattern of the logger messages.

<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>

Java SE provides the following standard formatter classes:

SimpleFormatter

It generates text messages with basic information.

XMLFormatter

It generates the messages in the XML format.

Post a comment