×

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log file is offered. We will explore more into the Java Logger API in this part. We'll also talk about the Java Logger class, the logging level, the components, the logging handlers or appenders, the logger formatters or layouts,

Logger in Java?

Logging is an API in Java that makes it possible to track down program problems. If a logging call is made by an application, the Logger logs that occurrence in the LogRecord. It is then passed to the necessary handlers or appenders. The formatter or layouts are used by the appenders to prepare this log entry before sending it to the console or file.

Needs for logger

  • It offers the entire application tracing information.
  •  The application keeps track of any critical failures that happen.

Elements of logging

Its Java Logging components are used by developers to make logs and deliver these logs in the correct format to the right destination. A Java logging API is made up of the three items listed below:

  1. Loggers
  2. Logging handlers or appender
  3. Logging formatters or layouts

Loggers

The log request is transmitted to the Logger objects by the client's code. These logger objects monitor a log level in which they are interested and refuse log requests that are below it.

In the other words, it's in charge of recording log entries. It then sends these records to the appropriate appender.

The Loggers devices are typically named entities. the things that are divided by the dot operator. java.net, java.awt, etc. are a few examples.

The hierarchy of the namespace, which would be presented, is managed by the LogManager.The alignment must match the packaging namespace. But strict adherence to it is not required. However, it won't appear inside the shared namespace. Another anonymous Logger can also be created.

In the logging namespace, the logger searches for the parent loggers.It is the logging namespace object that is closest to the current ancestor. It receives the following characteristics from its parent:

  • Handlers: A logger will log every message passed to a parent's handlers, recursively across the tree.
  •  Logging tiers: If null is supplied, then top non-null level is sought by progressing toward the parent.
  • Resource bundle names: Any logger that contains a null resource bundle name inherits the resource bundle name of any of its parents up the tree recursively.

Logger Handlers or appender

Using several handlers in a Java logger is possible thanks to the Java Logging API, as well as the handlers process the logs appropriately. In Java, there are five different logging handlers:

StreamHandler: An output stream receives the prepared log message.

FileHandler: It sends the log text in XML format to a single document or a group of continuously updating log files.

Socket handler: This feature uses the socket handler to write the log messages to remote TCP ports.

The recollection buffer log records are managed by the MemoryHandler.

The FileHandler & ConsoleHandler are indeed the two default handlers offered by the Java Logging API. By adding new functionality to the Handler class or any of its subclasses, we can create our own custom designs (like MemoryHandler, StreamHandler, etc.). The logging requirements determine which appenders should be used. If you are unsure of which appenders to use, it might affect the program's performance.

Example of a Custom java logging handler:

import java.util.logging.LogRecord;  
import java.util.logging.StreamHandler;  
public class MyHandler extends StreamHandler   
{  
@Override  
public void publish(LogRecord record)   
{  
//Publish your own logic  
super.publish(record);  
}  
@Override  
public void flush()   
{  
super.flush();  
}  
@Override  
public void close() throws SecurityException   
{  
super.close();  
}  
}

Logging Layouts or Formatters:

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:

It generates a text message that contains a lot of information. It produces summaries of log messages that are readable by people. For instance to print a log message to a console, the ConsoleHandler makes use of the class. For instance, the subsequent console message displays.

Nov 15, 2022 07:15:22 PM DemoClass main

SEVERE: An exception occurred.

XMLFormatter

The log message is generated 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:

  
  
  
  
2022-15-29T07:15:22  
1595664378  
0  
DemoClass  
SEVERE  
DemoClass  
main  
1  
An exception occurred.  
  
  

We can personalize and develop our own Formatter class simply extending the Formatter class. Any handlers can be used with the modified class.

You can utilize several layouts, including such HTML, JSON, Syslog, plain text, etc. if you're using logging frameworks.

Logger levels in 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 does have an integer value. Higher values correspond to higher priorities. There are a total of nine levels, including 2 distinct log levels and seven standard log levels. The very first 3 logger levels—FINEST, FINER, and Perfectly acceptable the extensive tracing data, which includes details about what is occurring in and what has just happened in the program.

Let's get into more depth about each logger level:

  • 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 application may have thrown.
  • FINE: Out of all of these, it stands for the most significant message.
  • CONFIG: It displays data pertaining to the application's configuration. The details could include the amount of memory and disk space.
  • INFO: The operator or other authorities may utilize the user's information.
  • WARNING: It happens as a result of user error. The application displays a warning if a user enters incorrect credentials.
  • SEVERE: It happens when the application displays some serious or severe problems. In certain conditions, the application cannot be processed. The database being unavailable and running out of memory are two common examples of a severe level.

Configuring the Logger Level:

The logging level can be configured with the following sentence.

The sentence offers information about application setup and set its logging level to CONFIG. Additionally, the log is generated from the given level to higher ones.

If we had the log level set to FINE, the resultant log would have the following values: CONFIG, INFO, WARNING, & SEVERE.

By simply altering the Logger's configuration, you also can set it in the configuration file, as demonstrated below:

..


..

Logger events:

You must specify a level while logging events in Java in order to categorize them quickly. The following approaches can be used to designate a category and mention a message:

Procedure 1:

logger.log(Level.INFO, “Display the message”);

We have provided its level INFO and also the text to be printed as Display message in the aforementioned sentence.

Procedure 2:

logger.info(“Display the message”);

The setLevel() method is used to ensure that the Java logging framework only records messages that seem to be at or above the INFO level.

Log Manager for Java:

The java.util.logging package contains the class known as LogManager in Java. It creates and updates the logger instances as well as keeping track of the overall logging setup. It can also be used to configure itself specifically for a given application. It includes the two items listed below:

  • The designated 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 initialized. This feature enables container applications (like EJB containers) to override the default LogManager class with their own subclass.

Java New Logger Creation:

Using the getLogger() method, we can simply generate Logger in Java. If a logger has been defined, it detects it and returns it; if not, it sets up a new logger for the named subsystem.

If it establishes a new logger, it will setup the LogManager, as well as the logger's log level, and deliver the output of the logging to its handlers. It'll be stored in the global namespace of LogManager.

Syntax:

public static Logger getLogger(String name)

As a parameter, the logger title is parsed. The offer or data type of the subsystem should be used as the basis for the logger name, which should be divided mostly by dot (.) operator. As an illustration, java.awt, java.net, etc.

If the logger name is not provided then, it generates an appropriate logger and raises NullPointerException.


Related Topics

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

Java Class Syntax

A class is a fundamental building piece in object-oriented programming. It can be characterised as a template that outlines the information and actions connected to the creation of a class....

3 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Java Integer parseUnsignedInt() method

The parseUnsignedInt() method of Java Integer class parses the string argument as an unsigned decimal integer. The second parameter parses the string argument as an unsigned integer in the radix specified...

2 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Java array list remove time complexity

Java: We know that java is one of the programming languages. The main feature of java which is not in C or object oriented programming language is platform independence. Not only the...

7 minutes read.

Difference between String Tokenizer and split Method in Java

Introduction Today, let us understand the difference between String Tokenizer and Split Method. First, let us learn about the String Tokenizer and Split method individually and then know about their differences String...

7 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

How to Convert Binary to Decimal in Java

How to Convert Binary to Decimal in Java There are two methods to convert binary to decimal. Using Integer.parseInt() method Using user-defined logic Using Integer.parseInt() method The parseInt() is a static method of...

2 minutes read.

Java Abstraction

Java Abstraction Abstraction is an advanced feature of Java to make it transparent. The main motive behind the abstraction is to deal with ideas, not with events. Abstraction is a process...

4 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

Java LinkedHashSet

LinkedHashSet in Java with Example Java LinkedHashSet extends HashSet and Implements the Set interface. It doesn’t contain only duplicate values like HashSet. It also permits the null elements. It maintains the order...

5 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.