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)