eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

Log4j 2 is a popular, open-source logging framework written in Java. It was introduced to overcome various architectural flaws of Log4j. It’s thread-safe, fast, and provides various improvements over its predecessor. It’s distributed under the open-source Apache Software License.

Log4j 2 is the latest and improved version of the classic Log4j framework that reached the end of its life on August 5, 2015. However, Log4j is still widely used in many Java enterprise applications as a logging framework.

In this tutorial, we’ll learn about Log4j 2, its benefits over Log4j, and how to configure its core components using the log4j2.properties file in Java.

2. Maven Setup

We’ll need the log4j-core dependency in our pom.xml to start with:

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.20.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.20.0</version>
</dependency>

We can find the latest version of log4j-core and log4j-api in the Maven Repository.

3. Log4j 2 Logger

Unlike in Log4j, where we use Logger.getLogger() to get a Logger instance with a specific name, in Log4j 2 we use LogManager.getLogger():

private static final Logger logger = LogManager.getLogger(Log4j2Example.class);

The LogManager reads the initial configuration parameters from a configuration file or a configuration class. A Logger is associated with LoggerConfig, which is associated with Appenders that actually deliver the log events.

If we call LogManager.getLogger() by passing the same (class) name, we’ll always get the reference of the same logger instance.

Both Logger and LoggerConfig are named entities. Each Logger references a LoggerConfig, which can reference its parent, thus achieving the same effect.

A Logger follows a named hierarchy. This means a LoggerConfig named “com.baeldung” is a parent of the LoggerConfig named “com.baeldung.foo“.

4. Log4j 2 Configuration

Unlike Log4j, which supports configuration only through properties and XML formats, we can define the Log4j 2 configurations using JSON, XML, YAML, or properties format. All these formats are functionally equivalent. Therefore, we can easily convert the configuration done in one format to any other.

Moreover, Logj2 supports automatic configuration, which means it’s capable of configuring itself automatically during initialization.

It scans and locates all the ConfigurationFactory plugins at the start and arranges them in weighted order from highest to lowest – the properties file has the highest precedence of the value of 8, followed by YAML, JSON, and XML.

This means if we have logging configurations in the form of both the properties file and the XML file, then the precedence will be given to the properties file.

5. The log4j2.properties File

When Log4j 2 was released, it didn’t have the support for configuration through the properties file. It started supporting the properties file from the release of version 2.4.

The default properties configuration file is always log4j2.properties. The Logger gets the reference of this file from the CLASSPATH.

However, if we need to use a different configuration file name, we can set it using the system property log4j.configurationFile.

The system property may refer to a local file system or may contain a URL. Log4j 2 provides a DefaultConfiguration if it cannot locate a configuration file. In this case, we get the logging output redirected to the console and the root logger level set to ERROR.

6. Syntax of the log4j2.properties File

The syntax of the log4j2.properties file isn’t the same as that of log4j.properties. In the log4j.properties file, every configuration starts with ‘log4j‘, while this has been omitted in the log4j2.properties configuration.

Let’s see the syntax of a general log4j2.properties file:

# The root logger with appender name 
rootLogger = DEBUG, STDOUT
  
# Assign STDOUT a valid appender & define its layout  
appender.console.name = STDOUT
appender.console.type = Console
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %msg%n  

Here, STDOUT is the name of the Appender. As discussed earlier, we can attach multiple appenders to a logger to direct logs to different destinations.

Also, we should define a root logger in every Log4j 2 configuration. Otherwise, a default root LoggerConfig that has an ERROR level and ConsoleAppender is used.

7. Examples

Now, let’s understand the log4j2.properties file configurations for different appenders with the help of some examples.

7.1. Sample Program

Let’s start with an example application that logs some messages:

public class Log4j2ConsoleAndFile {

    private static final Logger logger = LogManager.getLogger(Log4j2ConsoleAndFile.class);

    public static void main(String[] args) {
        logger.info("Hello World!");
        logger.debug("Hello World!");
    }
}

7.2. Console Logging

The console is the default place for logging messages if no configuration file is located. Let’s create a log4j2.properties configuration for the console Appender with the root logger and also define the logging level for it:

# Root Logger
rootLogger=DEBUG, STDOUT

# Direct log messages to stdout
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %C{1} - %msg%n

Here, we’ve defined a log4j2.properties file with the following specifications:

  • We’ve defined the level of the root logger as DEBUG. This means that we’ll get all the log events with level DEBUG and above. We’ve also defined a name for the appender as STDOUT.
  • Since we want to direct the logs to the console, we assigned the Appender type as Console. We should note that the word console in the key name is only a convention and not mandatory.
  • Then, we specify the pattern in which we want to print the log messages.

Let’s also understand the meaning of each of the conversion characters in the layout pattern that we’ve used:

  • %-5level adds the log-level information to each log statement. It signifies that the priority of the logging event is left-justified to a width of five characters.
  • %d adds the timestamp in the defined format.
  • %t adds the thread name to the log statement
  • %C{1} prints the qualified class name, optionally followed by package names (precision qualifier), that logs the specific log statement.
  • %msg prints the actual log message.
  • %n adds a new line after every log statement.

Thus, when we run our sample application, we get the following lines printed on the console:

[INFO ] 2023-08-05 23:04:03.255 [main] Log4j2ConsoleAndFile - Hello World!
[DEBUG] 2023-08-05 23:04:03.255 [main] Log4j2ConsoleAndFile - Hello World!

The class PatternLayout explains more about conversion characters that we can use based on our needs.

7.3. Multiple Destinations

As discussed earlier, we can redirect the log events to multiple destinations:

# Root Logger
rootLogger=INFO, STDOUT, LOGFILE

# Direct log messages to STDOUT
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %C{1} - %msg%n

# Direct to a file
appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName = baeldung/logs/log4j2.log
appender.file.layout.type = PatternLayout
appender.file.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %C{1} - %msg%n
appender.file.filter.threshold.type = ThresholdFilter
appender.file.filter.threshold.level = info

Here, we’ve used two appenders to redirect the log messages to both the file and console. We’ve named them STDOUT and LOGFILE. Additionally, we’ve added both appenders to the root logger.

To redirect the log messages to a file, we need to specify the file name with its location.

We’ve also used ThresholdFilter, which filters out the log messages with a certain log level and above. Finally, we’ve specified the threshold.level as INFO. Thus, all the log messages with level INFO or above will be printed to the file.

When we run our sample application, we get only the following line printed on the console as well as the log4j2.log file:

[INFO ] 2023-08-05 23:04:03.255 [main] Log4j2ConsoleAndFile - Hello World!

8. Conclusion

In this article, we explored Log4j 2 and its benefits over Log4j. We’ve also understood the syntax of a log4j2.properties file and some simple examples of configuring a log4j2.properties file.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
4 Comments
Oldest
Newest
Inline Feedbacks
View all comments