@log4j2 annotation in spring boot example

The @Log4j2 annotation in Spring Boot is used to enable logging in an application using the Log4j2 framework. Below are the steps to use the @Log4j2 annotation in a Spring Boot application:

Step 1: Add the Log4j2 Dependency Add the Log4j2 dependency to your project's build file (pom.xml for Maven or build.gradle for Gradle). This can be done by adding the following dependency:


Step 2: Enable Log4j2 Configuration By default, Spring Boot looks for a log4j2.xml or log4j2-spring.xml file in the classpath to configure Log4j2. Create a log4j2.xml file in the src/main/resources directory of your project. This file will contain the logging configuration for your application.

Step 3: Add @Log4j2 Annotation To enable logging in a Spring Boot class, simply add the @Log4j2 annotation to the class. This annotation is provided by the Log4j2 framework and it automatically configures logging for the annotated class.

For example:

import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

public class ExampleClass {
   // Class implementation

Step 4: Use Logging in the Class Once the @Log4j2 annotation is added to a class, you can use the logging capabilities provided by Log4j2. For example, you can use the log.debug(), log.info(), log.warn(), and log.error() methods to log messages at different log levels.

log.debug("This is a debug message");
log.info("This is an info message");
log.warn("This is a warning message");
log.error("This is an error message");

By following these steps, you can enable and use Log4j2 logging in your Spring Boot application using the @Log4j2 annotation. This allows you to have fine-grained control over your application's logging configuration and log messages.