Log4j 2 Getting Started Example
In this tutorial, we will show you how to configure the Log4j2 with log4j2.xml
file and print the logging to the console and a file.
1. Introduction
Printing messages to the console is an integral part of the development testing and the debugging of a Java program. If developers are working on a Server side application, where they cannot see what’s going on inside the server, then their only visibility tool is a log file.
Without logs, developers cannot do any debugging or see what’s going on inside the application. Though, Java has pretty handy System.out.println()
methods to print something on console, which can also be routed to log file but not sufficient for a real-world Java application.
If developers are running a Java program in Linux or Unix based systems, Log4j
or SLF4j
or any other logging framework offers a lot more features, flexibility, and improvement on message quality, which is not possible using the System.out.println()
statements.
1.1 What is Log4j2?
Log4j2 is the updated version of the popular and influential Log4j library, which is a simple, flexible, and fast Java-based logging framework. It is thread-safe and supports internationalization. We mainly have 3 components to work with Log4j
:
- Logger: It is used to log the messages.
- Appender: It is used to publish the logging information to the destination like the file, database, console etc.
- Layout: It is used to format logging information in different styles.
1.1.1 Log4j2 Logger Class
Logger
class provides the methods for the logging process. We can use the LogManager.getLogger()
method to get the Logger
object. The syntax is given below:
static Logger log = LogManager.getLogger(YourClassName.class);
Logger
class has 5 different logging methods which are used to print the status of an application:
Description | Method Syntax | |
---|---|---|
debug(Object message) | It is used to print the message with the level org.apache.logging.log4j.Level.DEBUG . | public void debug(Object message) |
error(Object message) | It is used to print the message with the level org.apache.logging.log4j.Level.ERROR . | public void error(Object message) |
info(Object message) | It is used to print the message with the level org.apache.logging.log4j.Level.INFO . | public void info(Object message) |
fatal(Object message) | It is used to print the message with the level org.apache.logging.log4j.Level.FATAL . | public void fatal(Object message) |
warn(Object message) | It is used to print the message with the level org.apache.logging.log4j.Level.WARN . | public void warn(Object message) |
trace(Object message) | It is used to print the message with the level org.apache.logging.log4j.Level.TRACE . | public void trace(Object message) |
To summarize, the priority level is given below.
Trace < Debug < Info < Warn < Error < Fatal
Where org.apache.logging.log4j.Level.FATAL
has the highest priority and org.apache.logging.log4j.Level.Trace
the lowest.
1.1.2 Log4j2 Appender Interface
Appender
is an interface which is primarily responsible for printing the logging messages to the different destinations such as console, files, sockets, database etc. In Log4j2
we have different types of Appender
implementation classes.
1.1.3 Log4j Layout Class
Layout
component specifies the format in which the log statements are written into the destination repository by the Appender
. In Log4j2
we have different types of Layout
implementation classes.
1.2 Why prefer Log4j2 over System.out.println?
Below are some of the reasons, which are enough to understand the limitation of using System.out.println()
:
- Any logging framework including allows developers to log debugging information with a log level which can be used as filtering criteria, i.e. one can disable the message belongs to a particular log level. For e.g., Developers would be more concerned to see the
WARN
messages thanDEBUG
messages in the production environment - Logging framework can produce better outputs and metadata which helps to troubleshoot and debug. For e.g.,
Log4j2
allows to print formatted output by specifying a formatting pattern i.e. by usingPatternLayout
one can include a timestamp, class name etc
Now, open up the Eclipse Ide and let’s start building the application!
2. Log4j2 Getting Started Example
Below are the steps involved in developing this application.
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8, and Log4j2 Jar. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location‘ will be selected. Select the ‘Create a simple project (skip archetype selection)‘ checkbox and just click on next button to proceed.
It will ask you to ‘Enter the group and the artifact id for the project‘. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on finish and the creation of a maven project will be completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Log4j2Example </groupId> <artifactId>Log4j2Example </artifactId> <version>0.0.1-SNAPSHOT</version> </project>
We can start adding the dependencies that developers want like Log4j2, Junit etc. Let’s start building the application!
3. Application Building
Below are the steps involved in developing this application.
3.1 Maven Dependencies
In this example, we are using the most stable Log4j2 version in order to set-up the logging framework. The updated file will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Log4j2Example</groupId> <artifactId>Log4j2Example</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.8.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.8.2</version> </dependency> </dependencies> </project>
3.2 Java Class Creation
Let’s create the required Java files. Right-click on src/main/java
folder, New -> Package
.
A new pop window will open where we will enter the package name as: com.jcg.logging
.
Once the package is created, we will need to create the implementation class. Right-click on the newly created package, New -> Class
.
A new pop window will open and enter the file name as: Log4j2Example
. The implementation class will be created inside the package: com.jcg.logging
.
3.2.1 Implementation of Utility Class
Let’s write a quick Java program and write the logs in the console and then in a sample file by using the Log4j2
configuration. Add the following code to it:
Log4j2Example.java
package com.jcg.logging; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Log4j2Example { private static final Logger LOG = LogManager.getLogger(Log4j2Example.class); public static void main(String[] args) { LOG.debug("This Will Be Printed On Debug"); LOG.info("This Will Be Printed On Info"); LOG.warn("This Will Be Printed On Warn"); LOG.error("This Will Be Printed On Error"); LOG.fatal("This Will Be Printed On Fatal"); LOG.info("Appending string: {}.", "Hello, World"); } }
3.3 Log4j Configuration File
Log4j2
will be usually configured using a properties file or XML file. So once the log statements are in place developers can easily control them using the external configuration file without modifying the source code. The log4j2.xml
file is a Log4j2
configuration file which keeps properties in key-value pairs. By default, the LogManager
looks for a file named log4j2.xml
in the CLASSPATH
.
To configure the logging framework, we need to implement a configuration file i.e. log4j2.xml
and put it into the src/main/resources
folder. Add the following code to it:
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?> <Configuration xmlns="http://logging.apache.org/log4j/2.0/config"> <Properties> <Property name="basePath">../Log4j2Example/logs</Property> </Properties> <Appenders> <!-- File Appender --> <File name="FILE" fileName="${basePath}/logfile.log" append="true"> <PatternLayout pattern="%-5p | %d{yyyy-MM-dd HH:mm:ss} | [%t] %C{2} (%F:%L) - %m%n" /> </File> <!-- Console Appender --> <Console name="STDOUT" target="SYSTEM_OUT"> <PatternLayout pattern="%-5p | %d{yyyy-MM-dd HH:mm:ss} | [%t] %C{2} (%F:%L) - %m%n" /> </Console> </Appenders> <Loggers> <Logger name="com.jcg" level="debug" /> <Root level="info"> <AppenderRef ref="STDOUT" /> <AppenderRef ref="FILE" /> </Root> </Loggers> </Configuration>
4. Run the Application
To run the application, Right click on the Log4j2Example
class, Run As -> Java Application
. Developers can debug the example and see what happens after every step. Enjoy!
5. Project Demo
When we will execute the example the console output and the sample log file will look like as follows.
That’s all for this post. Happy Learning!!
6. Conclusion
That’s all for getting the developers started with the Log4j2 example. I hope this article served you whatever you were looking for. Developers can download the sample application as an Eclipse project in the Downloads section.
7. Download the Eclipse Project
This was an example of Log4j2 Example.
You can download the full source code of this example here: Log4j2Example