DEV Community

Arun Kumar
Arun Kumar

Posted on

# πŸš€ Complete Guide to Log4j2 in Java (Beginner to Advanced)

Logging is one of the most important parts of any application. Without logs, debugging issues in production becomes extremely difficult. In Java, one of the most powerful and widely used logging frameworks is Log4j2.

This blog will help you understand Log4j2 from basics to practical usage in a Spring Boot project.


πŸ“Œ What is Log4j2?

Log4j2 is a logging framework developed by Apache. It is used to record application events such as:

  • Application start/stop
  • Errors and exceptions
  • User activity
  • Debug information

πŸ‘‰ It is an improved version of Log4j (Log4j1).


⚑ Why Use Log4j2?

Log4j2 is preferred because it offers:

βœ” High performance
βœ” Flexible configuration (XML, JSON, YAML)
βœ” Multiple output options (Console, File, Database)
βœ” Different log levels
βœ” Asynchronous logging support


πŸ“Š Log Levels in Log4j2

Log levels help categorize logs based on severity:

Level Description
TRACE Detailed debugging
DEBUG Developer debugging
INFO Normal application flow
WARN Warning messages
ERROR Something went wrong
FATAL Critical failure

πŸ“¦ How to Add Log4j2 in Spring Boot

Add this dependency in pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ This replaces default logging with Log4j2.


🧱 Basic Logger Example

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Demo {
    private static final Logger logger = LogManager.getLogger(Demo.class);

    public static void main(String[] args) {
        logger.info("Application started");
        logger.error("Something went wrong");
    }
}
Enter fullscreen mode Exit fullscreen mode

βš™οΈ Log4j2 Configuration (log4j2.xml)

Log4j2 uses a configuration file:

src/main/resources/log4j2.xml
Enter fullscreen mode Exit fullscreen mode

πŸ–₯️ Console Logging

<Console name="Console" target="SYSTEM_OUT">
    <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5level %logger - %msg%n"/>
</Console>
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Prints logs in terminal


πŸ“ File Logging

<RollingFile name="FileLogger"
             fileName="logs/app.log"
             filePattern="logs/app-%d{yyyy-MM-dd}.log">
    <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c - %m%n"/>
</RollingFile>
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Stores logs in files with daily rotation


πŸ—„οΈ Database Logging (Advanced)

<JDBC name="DatabaseAppender" tableName="logs">
    <DriverManager 
        connectionString="jdbc:postgresql://localhost:5432/arundb"
        userName="postgres"
        password="password"/>

    <ColumnMapping name="log_date" type="java.sql.Timestamp"/>
    <ColumnMapping name="level" pattern="%level"/>
    <ColumnMapping name="logger" pattern="%logger"/>
    <ColumnMapping name="message" pattern="%message"/>
</JDBC>
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Saves logs directly into database


πŸ”— Connecting Appenders

<Root level="info">
    <AppenderRef ref="Console"/>
    <AppenderRef ref="FileLogger"/>
    <AppenderRef ref="DatabaseAppender"/>
</Root>
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Sends logs to multiple destinations


πŸ”„ Logging Flow

Application β†’ Logger β†’ Appenders β†’ Output (Console/File/DB)
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Example in Spring Boot Controller

@RestController
public class UserController {

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

    @GetMapping("/test")
    public String test() {
        logger.info("API called");
        return "Success";
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)