Inject Logger in Spring

Introduction

When outputting Log in Java, use libraries such as Log4j and Logback, or use java.util.logging. Most libraries and APIs get and generate Logger instances as follows.

Logger logger = Logger.getLogger(Hoge.class);

Writing these in every class is a hassle. Let's find a simpler way to write using Spring.

Former story

It's almost an introduction to the implementation of this site. http://memorynotfound.com/spring-inject-logger-annotation-example/

Thank you.

Logger Injection by Spring

If you are using Spring, you can inject Logger into the annotated filed as below.

    @Log
    private static Logger logger;

The amount of description is small, but it is not necessary to specify the argument class, so you can eliminate Logger's mistake (which should sometimes be copied and pasted).

I will explain how to implement it.

Log annotation

Create a Log annotation as shown below.

Log.java


@Retention(RUNTIME)
@Target(FIELD)
@Documented
public @interface Log {
}

Since it is referenced at runtime, it is @Retention (RUNTIME), and since the target is a field, it is @Target (FIELD).

LogInjector

Using Spring, write the code to inject Logger in the field with the @Log annotation created earlier.

Create a BeanPostProcessor implementation of Spring as follows, and create a Logger in it.

@Component
public class LogInjector implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(final Object bean, String name) throws BeansException {
        ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                // make the field accessible if defined private
                ReflectionUtils.makeAccessible(field);
                if (field.getAnnotation(Log.class) != null) {
                    Logger log = Logger.getLogger(bean.getClass());
                    field.set(bean, log);
                }
            }
        });
        return bean;
    }

}

how to use

Now you are ready. After that, you can use it by following the steps below.

Now you don't have to do getLogger every time.

Recommended Posts

Inject Logger in Spring
Use Interceptor in Spring
Microservices in Spring Cloud
Get cookies in Spring
Set context-param in Spring Boot
Spring Boot 2 multi-project in Gradle
Error in Spring database connection
Major changes in Spring Boot 1.5
NoHttpResponseException in Spring Boot + WireMock
Loop step in Spring Batch
How to use Lombok in Spring
Call Chain from Chain in Spring Integration
Spring Boot Hello World in Eclipse
Spring Boot application development in Eclipse
Java Spring environment in vs Code
Write test code in Spring Boot
I participated in JJUG CCC 2019 Spring
Implement reCAPTCHA v3 in Java / Spring
Store session information in database in Spring Session
Implement REST API in Spring Boot
What is @Autowired in Spring boot?
Event processing is performed in Spring.
Implement Spring Boot application in Gradle
Thymeleaf usage notes in Spring Boot
Spring Autowired is written in the constructor
Launch (old) Spring Boot project in IntelliJ
Convert request parameter to Enum in Spring
Build Spring Boot + Docker image in Gradle
Static file access priority in Spring boot
How to include Spring Tool in Eclipse 4.6.3?
Exists using Specification in Spring Data JPA
Output Spring Boot log in json format
Local file download memorandum in Spring Boot
Handle system environment variables in Spring application.properties
Create Java Spring Boot project in IntelliJ
Loosen Thymeleaf syntax checking in Spring Boot
Error in implementation when implementing Spring validation
Separate Task Executors used in Spring @Async
[Practice! ] Display Hello World in Spring Boot
How Dispatcher servlet works in Spring MVC
Use DynamoDB query method in Spring Boot
Null support cache in Spring Data Redis
To write Response data directly in Spring
Major changes in Spring Framework 5.0 core functionality
What I got into @Transactional in Spring
Switching beans by profile annotation in Spring
DI SessionScope Bean in Spring Boot 2 Filter
[Java] [Spring] Test the behavior of the logger
[* Java *] I participated in JJUG CCC 2019 Spring
Maven configuration problem in Spring pom.xml in Eclipse
Change session timeout time in Spring Boot
File output bean as JSON in spring