본문 바로가기
IT/Spring

AOP 사용하여 로깅

by 봉즙 2023. 9. 25.

@GetMapping, @PostMapping, @PutMapping, @DeleteMapping 을 사용하는 메서드를 찾아서 로깅을 해주는 방식이다.

getPointCut()에 return을 주지 않으면 데이터가 유실되는 현상이 나타나므로 return을 붙여줘야한다.

getBody()에서는 사용된 어노테이션중 RequestBody를 찾아서 데이터를 가져 오도록 처리 하였다.

@Aspect
@Component
class ApiLogAop {
    private val logger = KotlinLogging.logger {}

    @Pointcut(
        "@annotation(org.springframework.web.bind.annotation.GetMapping) ||"
                + "@annotation(org.springframework.web.bind.annotation.PostMapping) ||"
                + "@annotation(org.springframework.web.bind.annotation.PutMapping) ||"
                + "@annotation(org.springframework.web.bind.annotation.DeleteMapping)"
    )
    fun getPointCut() {
    }

    @Around(value = "getPointCut()")
    fun getAround(proceedingJoinPoint: ProceedingJoinPoint): Any {
        return info(proceedingJoinPoint)
    }

    private fun info(proceedingJoinPoint: ProceedingJoinPoint):Any {
        val signature = proceedingJoinPoint.signature as MethodSignature
        val body = getBody(proceedingJoinPoint, signature)
        val response = proceedingJoinPoint.proceed() as? ResponseEntity<Any> ?: ResponseEntity.ok("")

        logger.info { "[ASPECTJ AOP Request] ${signature.declaringTypeName} ${signature.name} body : $body" }
        logger.info { "[ASPECTJ AOP Response] ${signature.declaringTypeName} ${signature.name} body : ${response.body}" }
        return response
    }


    private fun getBody(
        proceedingJoinPoint: ProceedingJoinPoint,
        methodSignature: MethodSignature
    ): Any? {
        val annotationMatrix = methodSignature.method.parameterAnnotations
        var index = -1
        for (annotations in annotationMatrix) {
            index++
            for (annotation in annotations) {
                if (annotation is RequestBody) {
                    return proceedingJoinPoint.args[index]
                }
            }
        }
        return null
    }

}

 

 

https://github.com/hanbong5938/practice/tree/master/logging

'IT > Spring' 카테고리의 다른 글

Spring AOP 분석  (0) 2023.10.10
RestControllerAdvice 사용하여 로깅  (0) 2023.09.25
Interceptor를 사용하여 Request/Reponse Logging  (0) 2023.09.20
Private Method Test 하기  (0) 2023.09.14
Annotation Bean register  (0) 2023.09.07

댓글