본문 바로가기
Back-End/Spring

Spring AOP : @Before와 Request로 ServletPath Logging

by sharekim 2021. 3. 21.

어제 수많은 구글링과 시도 끝에 @Before로 ServletPath를 Logging 하는 데 성공했다.

 

AOP를 위해 작성한 Class LogAdvice의 코드는 다음과 같다

@Aspect
@Component
@Slf4j
public class LogAdvice {

	@Autowired
	UserService service;
	
	@Before("execution (* com.cafe24.healthshare.controller.*Controller.*(..))")
	public void doLogging() throws Throwable{
		HttpServletRequest request = 
		        ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
		log.info(request.getMethod()+" : "+request.getServletPath());
	}
	
}

AOP 클래스를 만드는 방법(@Aspect 어노테이션 달기 등)은 구글링 해보면 쉽게 나오니 패스하고

 

방법은 간단하다.

 

1. 메서드에 @Before를 수행할 JoinPoint를 설정해주고

2. 메서드에서 HttpServletRequest를 RequestContextHolder로부터 호출하면 된다.

 

나는 개인적으로 Method(GET인지 POST인지)와 ServletPath를 log로 남기도록 했다.

'Back-End > Spring' 카테고리의 다른 글

JpaRepository  (0) 2021.05.12
엔티티 클래스  (0) 2021.05.12
Spring Context Root 경로 (Resources 경로)  (0) 2021.03.21
Spring AOP 용어 정리  (0) 2021.03.21
Spring AOP : pointcut is malformed  (0) 2021.03.20

댓글