1.ログセクション
package com.example.demo.aspect;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Aspect
@Component
@EnableAspectJAutoProxy
@Slf4j
public class LogAspect {
@Pointcut("execution(* com.example.demo.controller.*Controller.*(..))")
public void executionService() {
}
@Around("executionService()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sa = (ServletRequestAttributes) ra;
HttpServletRequest request = sa.getRequest();
Object[] args = joinPoint.getArgs();
List<Object> logArgs = Arrays.asList(args).stream()
.filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)))
.collect(Collectors.toList());
log.info("url : {}", request.getRequestURL());
Gson gson = new Gson();
log.info("req params : {}", gson.toJson(logArgs.get(0)));
Object result = joinPoint.proceed();
log.info("resp : {}", gson.toJson(result));
return result;
}
@AfterReturning("executionService()")
public void doAfter(JoinPoint joinPoint) {
}
}
2.試験方法
@PostMapping("/test")
@ResponseBody
public Map<String, Object> getMsg(String id, String name) {
Map<String, Object> map = new HashMap<>();
map.put("result", "response msg");
map.put("id", id);
map.put("name", name);
return map;
}
3.効果を見る
2021-01-01 22:13:55.404 INFO 2236 --- [nio-8080-exec-1] com.example.demo.aspect.LogAspect : url : http://localhost:8080/test
2021-01-01 22:13:55.404 INFO 2236 --- [nio-8080-exec-1] com.example.demo.aspect.LogAspect : req params : "100"
2021-01-01 22:13:55.418 INFO 2236 --- [nio-8080-exec-1] com.example.demo.aspect.LogAspect : resp : {
"result":"response msg","name":"zhangsan","id":"100"}