aop 사용한 로깅

aop 를 활용한 로그를 남기려 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/basic.xml"/>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%green(%d{yyyy-MM-dd HH:mm:ss.SSS}) [%thread] %highlight(%-5level) %cyan(%logger{36}) - %msg%n
            </pattern>
        </layout>
    </appender>
    <root level="INFO">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

point cut 으로 get post put delete 어노테이션이 있는 메서드들에 대해서 작동하도록 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Component
@Aspect
@Slf4j
@RequiredArgsConstructor
public class ApiLog {

    @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)")
    public void logInfo() {
    }

    @Around(value = "logInfo()")
    public Object aspectGet(final ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        return this.getObject(proceedingJoinPoint);
    }

    private Object getObject(final @NotNull ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        final HttpServletRequest request =
                ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))
                        .getRequest();
        log.info("url : {}", request.getRequestURI());
    }
}