Log4j 2 simple example

By | January 15, 2022

In this post, We look at Log4j 2 simple example.

Log4j2 is the updated version of the popular Apache library. It is used extensively throughout Java applications for so many years. The Apache Log4j 2 carries all the basic logging features of its predecessor and is built with some important improvements, importantly in the area of performance.

And of course, As you know how instrumental logging is for any application, both for debugging and audit purposes, selecting a solid logging library is quite an important decision for any application.

In the following sections, we’re going to take a look at how to use the log4j2 library.

pom.xml

We have added log4j2  log4j-api & log4j-core dependency in the dependencies section.

log4j2.xml

We have to create a log4j2.xml configuration file on the classpath(src/main/resources):

Let’s have a closer look at the tags used in the log4j2.xml configuration:

  • Configuration: This is the root element in a log4j2 configuration file. The status attribute is used to represent the level at which internal log4j events should be logged
  • Appenders: This element mainly holds a list of appenders. In our example, an appender corresponding to the System console(SYSTEM_OUT) is defined
  • LoggersThis element usually holds a list of Logger instances. The Root element is a standard logger that is used to set the default log level to output all log messages

NOTE: It’s important to note that the Root logger is mandatory in every logger configuration file. if you don’t set a value for the root logger then it will automatically be configured by default with a Console appender and the ERROR log level.

ClientTest.java

Now we are going to test our logger. For this, I’ve written below test class.

If you run ClientTest.java as a java application then you’ll find the below output: 

11:22:53.905 [main] INFO com.kkjavatutorials.client.ClientTest – Logging info message
11:22:53.906 [main] WARN com.kkjavatutorials.client.ClientTest – Logging warn message
11:22:53.907 [main] ERROR com.kkjavatutorials.client.ClientTest – Logging error message

You May Also Like:
Why Logging?
How to Create a Custom Appender in log4j2?

That’s All about Log4j 2 simple example

Leave a Reply

Your email address will not be published.