×

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted in Java 1.4. The log file can be recorded using this capability. This section will include a thorough analysis of the Java Logger API. We will also talk about the components, the logging handlers or appenders, the logging formatters or layouts, the logging level, the Java Logger class, and the components. It shows how the handlers are handled in the efficient manner and so on, this come across with the covering of every required topic.

What exactly does Java logging?

The Java language has an API called logging that makes it possible to track down programme failures. The event is entered into the LogRecord by the Logger when an application generates the logging call. It then sends to the appropriate handlers or appenders. The appenders format the log record using a formatter or layouts before sending it to the console or file.

Desire for Logging

  • It offers the application's full history of tracing information.
  • If any critical failures occur while running the application, it notes them.

Logging component

The Java Logging components are used by the developers to produce logs and transmit them in the appropriate format to the desired location. The following three components make up the Java logging API:

  • Loggers
  • Handlers or Appenders for Logging
  • Layouts or Formatters for Logging

Loggers

The Logger objects receive the log request from the client's code and process it. These logger objects maintain a log level that they are interested in and deny requests for logs that are below it.

It is in charge of recording log records, in other words. The records are then sent on to the appropriate appender.

Typically, named entities make up the Loggers objects. objects that are separated by a dot operator. java.net, java.awt, etc. are a few examples.

The namespace is controlled by the LogManager and is organised hierarchically. It must match the packaging namespace in alignment. Although it is not necessary to adhere to it precisely. Although it won't show up in the shared namespace, we can also build an anonymous Logger.

The Logger looks for the parent loggers in the namespace for logging. It is the namespace in logging that is most similar to the current ancestorIt's important to know that the root logger is an orphan. It receives a variety of traits from their parent, including:

  • Levels of Logging: If null is supplied, it searches for the top non-null level by moving toward the parent.
  • Handlers: Any message sent to the parent's handlers will be logged by a logger, recursively up the tree.
  • Names of resource bundles: In the event that a logger's resource bundle name is null, it will recursively up the tree inherit the resource bundle name of any parent.

Handlers or Appenders for Logging

  • A Java logger can employ several handlers, and these handlers process the logs appropriately thanks to the Java Logging API. There are five distinct logging handlers available in Java:
  • StreamHandler: The prepared log message is written to an OutputStream.
  • ConsoleHandler: It outputs to the console all of the prepared log messages.
  • Handleroffile: The log message is written in XML format either to a single file or a collection of files that rotate continually.
  • SocketHandler: The external TCP ports are used to write the log message.
  • MemoryHandler: The buffer log records that are memory-resident are managed by it. The ConsoleHandler and FileHandler are the two standard handlers that are provided by the Java Logging API. The Handler class can be modified and extended by creating new instances of it or any of its subclasses (such as MemoryHandler, StreamHandler, etc.). Depending on the logging requirements, the appenders are chosen. The effectiveness of the application may be impacted if you are unsure which appenders to employ.

Layouts or Formatters for Logging

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

A text message containing broad information is produced by it. It creates log message summaries that are readable by humans. To print the log message to the console, the ConsoleHandler makes use of the class. For instance, the subsequent console message displays

Nov 207, 2022 02:55:55 PM DemoClass main  
Server: There was an exception.

XMLFormatter

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

<?xml version="2.0" encoding="UTF-10" standalone="nope"?>  
<!DOCTTYPE log SYSTEM "logger.dtd">  
<log>  
<record>  
<Date>2022-12-31T11:59:55</Date>  
<millins>1595664378</millins>  
<order>0</order>  
<logger>DemoClass</logger>  
<levels>SEVERE</levels>  
<class3>DemoClass</class3>  
<method1>main</method1>  
<thread2>1</thread2>  
<text>An exception has occurred.</text>  
</record>  
</log>  

level We can personalise and construct our own Formatter class by extending the Formatter class. Any handlers can use the modified class.

Other styles, including plain text, Syslog, json, html, etc., can be used if you're using logging frameworks.

Logging Levels of the 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 has an integer value. Higher values correspond to higher priorities. In total, there are nine levels: seven standard log levels and two special log levels. The first three logging levels—FINEST, FINER, and FINE—represent the extensive tracing data, which includes details about what is occurring in the application and what happened in the application. Let's go over each level of logging in more detail.

  • 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 programme may have thrown.
  • FINE: Out of all of these, it stands for the most significant message.
  • CONFIG: It displays data pertaining to the settings of the application. The details could include how much memory and disc space there is.
  • INFO: Users' personal data is used by administrators and other authorities.
  • WARNING: It occurs due to user mistake. If a user inputs the wrong credentials, the application shows a warning.
  • The SEVERE: It happens when the application displays some serious or severe problems. The application is unable to proceed in such circumstances. The database being unavailable and running out of memory are two common examples of a severe level.

Establishing the Logging Level

The logging level can be configured with the following sentence.

logger.setLevel(Level.CONFIG); 

In addition to providing information about the application's setup, the aforementioned line also sets the logging level to CONFIG. Additionally, it creates a log that extends from the level that is provided to higher levels.

The output logs would have been CONFIG, INFO, WARNING, and SEVERE if the log level had been set to FINE.

As we've demonstrated below, we can also assign it to the configuration file by simply modifying the Logger's settings:

...  
<Loggers>  
<Logger naam="HintLogger" level="message">  
...  

Events of the logging

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

First method

logger.log(Level.Message, "Display the information");

The level Message and information to be printed are both given in the previous sentence.

Second method

logger.data("Display information"); 

The setLevel() method is used to ensure that only events with a level of INFO or above are logged by the Java logger.

Log Manager for Java

The class java.util.logging contains the LogManager, which is a component of Java. The logger instances are created and maintained, and the global logging settings is tracked. Additionally, we may use it to configure it for our own application-specific needs. These two items are included in it:

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

Frameworks for Logging

The logging framework can also be used to simplify the logging notion. The following well-known logging framework is employed for logging:

  • Log4j: A Java-based logging tool called Apache Log4j is open-source.
  • SLF4J:  Simple Logging Facade for Java is what it is called (SLF4J). For several logging frameworks, including Java.util.logging, Log4j, and Logback, it serves as an abstraction layer.
  • Logback: Prior to the release of Log4j version 2, it was developed as an open-source project to serve as a successor.

Related Topics

PriorityQueue in Java

PriorityQueue in Java A PriorityQueue is a member of the Java Collection Framework and is used when the values are needed to be processed based on priority. Priority queue operates similar to...

8 minutes read.

Root exception in java

Java: The main feature of java which is not in C or object oriented programming language is platform independence. Not only the platform independence there are many other features in java...

3 minutes read.

Java String Reader

StreamReaderClass: This class is present in the java.io package. It is a character stream in which string act as a source.This method provides to read characters from a string. Character Stream: This class...

3 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

Composition in Java

Composition Java uses the composition method to implement a has-a connection. Composition allows us to reuse code in the same way that Java inheritance does. The "is-a" relationship is implemented using the...

3 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Java String vs StringBuffer

Java String vs StringBuffer In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes. String...

4 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.