×

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

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR. Truth table: XYXNOR001010100111 If the bits are the same, it returns 1, else it returns 0. Examples:  Input: 10 20 Output : 1 A Binary...

3 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

The Diamond Operator in Java 7

The Diamond operator is a comparatively recent Java operator originally developed in JDK 7 to enhance type identification and eliminate boilerplate Java code. The Diamond operator is characterized by a...

2 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

Java Math toIntExact() Method

The toIntExact() method of Java Math class returns the int value of the given long argument, throwing an exception if the value overflows an int. Syntax: public static int toIntExact (long value) Parameters: The...

2 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

How to remove last character from String in Java

In java, there are predominantly three classes connected with the string. The classes are String, StringBuilder, and StringBuffer class that gives techniques connected with string control. Eliminating the first and...

5 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Java Macros

Macros are additions to the JDK 7 compiler in Java. Compile time macros are added and supported. Macros are Java classes that are instantiated and executed during the compilation process....

2 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.