Controller 단의 각 메서드 시작, 끝에 파라미터와 리턴값을 logging하자
in SampleController
@Slf4j
@RestController
@RequiredArgsConstructor
public class SampleController {
private final SampleService sampleService;
@GetMapping("/sample/request")
public String request(RequestDto dto) {
log.info("###Start request {}", "request");
log.info("\t{}", dto.toString());
sampleService.sampleRun(dto.getId());
String result = "ok";
log.info("###End request {}", "request");
log.info("\t{}", result);
return result;
}
@GetMapping("/sample/request2")
public String request2(RequestDto dto) {
log.info("###Start request {}", "request2"); //중복
log.info("\t{}", dto.toString()); //중복
sampleService.sampleRun2(dto.getId());
String result = "ok2";
log.info("###End request {}", "request2"); //중복
log.info("\t{}", result); //중복
return result;
}
}
@RestController
@RequiredArgsConstructor
public class SampleController {
private final SampleService sampleService;
@GetMapping("/sample/request")
public String request(RequestDto dto) {
sampleService.sampleRun(dto.getId());
return "ok";
}
@GetMapping("/sample/request2")
public String request2(RequestDto dto) {
sampleService.sampleRun2(dto.getId());
return "ok2";
}
}
implementation 'org.springframework.boot:spring-boot-starter-aop'
Application 클래스 혹은 @Configuration 추가한 클래스에 추가하기
@Component
@Aspect
@Slf4j
public class LogAspect {
//...
}
: 특정 기능을 적용시킬 그룹을 설정
@Pointcut("within(com.example.log_prac.controller.*)") // 패키지 범위 설정
public void controller() {}
: 메서드가 실행되기 전에 동작
@Before("controller()")
public void beforeRequest(JoinPoint joinPoint) {
log.info("###Start request {}", joinPoint.getSignature().toShortString());
Arrays.stream(joinPoint.getArgs())
.map(Object::toString)
.map(str -> "\t" + str)
.forEach(log::info);
}
: 메서드가 return값을 반환 후 동작
@AfterReturning(pointcut = "controller()", returning = "returnValue")
public void afterReturningLogging(JoinPoint joinPoint, Object returnValue) {
log.info("###End request {}", joinPoint.getSignature().toShortString());
if (returnValue == null) return;
log.info("\t{}", returnValue.toString());
}
: Exception 발생 후 동작
@AfterThrowing(pointcut = troller()", throwing = "e")
public void afterThrowingLogging(JoinPoint joinPoint, Exception e) {
log.error("###Occured error in request {}", joinPoint.getSignature().toShortString());
log.error("\t{}", e.getMessage());
}