Back-end/java

완전 간단하게 AOP로 log찍기

Nellie Kim 2023. 9. 26. 11:47
728x90

1. 종속성 추가

implementation 'org.springframework.boot:spring-boot-starter-aop'

 

2. main 클래스에 @EnableAspectJAutoProxy 추가

@EnableAspectJAutoProxy // AOP 활성화
public class FirstApplication {
    public static void main(String[] args) {
        SpringApplication.run(FirstApplication.class, args);
    }
}

 

3. AOP Aspect 클래스 생성

package com.example.first.aop;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
@RequiredArgsConstructor
public class LogAopComponent {
    private Logger logger = LoggerFactory.getLogger(LogAopComponent.class);

	// 적용하고 싶은 경로 적어주기
    @AfterReturning(pointcut = "execution(* com.example.first..*(..))", returning = "result")
    public void logMethodExecution(Object result) {
        log.info("test");
    }
}

경로는 모든 프로젝트의 디렉토리로 설정했다.

 

이렇게 하면, 

프로젝트 내 모든 메서드가 실행될 때, test 로그가 찍히는 것을 볼 수 있다!!!