AOP面向切面编程:为Controller类中方法增加日志打印功能

AOP面向切面编程(动态代理):为Controller控制类中的方法增加日志打印的功能

1、pom文件中增加Spring中aop的坐标依赖;

  <!--aop打印日志-->

  <dependency>

    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    <version>2.2.6.RELEASE</version>
  </dependency>

 

2、增加Controller控制类中的日志切面类;

@Aspect
@Component
@Slf4j
public class LogAopAspect {

@Pointcut("execution(public * com.xxx..controller.*.*(..))")
public void controllerWebLog() {
}

@Before("controllerWebLog()")
public void doBefore(JoinPoint joinPoint) {
try {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
log.info("请求开始 : " + "********************************************");
// 只记录post方法
if("POST".equals(request.getMethod())){
log.info("请求URL : " + request.getRequestURL());
log.info("客户端ip ["+ request.getRemoteAddr() +"]");
log.info("请求映射 : 【" + joinPoint.getSignature().getDeclaringTypeName() + "】类的【" + joinPoint.getSignature().getName() + "】方法");

// 获取参数, 只取自定义的参数, 自带的HttpServletRequest, HttpServletResponse不管
if (joinPoint.getArgs().length > 0) {
for (Object o : joinPoint.getArgs()) {
if (Objects.isNull(o) || o instanceof MultipartFile || o instanceof MultipartFile[] || o instanceof HttpServletRequest || o instanceof HttpServletResponse) {
continue;
}
log.info("请求参数 : " + JSONObject.toJSONString(o));
}
}
}
// 只记录post方法
if("GET".equals(request.getMethod()) || "PUT".equals(request.getMethod()) || "DELETE".equals(request.getMethod())){
// 记录下请求内容
log.info("请求URL : " + request.getRequestURL());
log.info("请求IP : " + request.getRemoteAddr());
log.info("请求映射 : 【" + joinPoint.getSignature().getDeclaringTypeName() + "】类的【" + joinPoint.getSignature().getName() + "】方法");

// 获取参数, 只取自定义的参数, 自带的HttpServletRequest, HttpServletResponse不管
if (joinPoint.getArgs().length > 0) {
for (Object o : joinPoint.getArgs()) {
if (Objects.isNull(o) || o instanceof MultipartFile || o instanceof MultipartFile[] || o instanceof HttpServletRequest || o instanceof HttpServletResponse) {
continue;
}
log.info("请求参数 : " + JSONObject.toJSONString(o));
}
}
}
}catch (Exception e){
e.printStackTrace();
}
}

@AfterReturning(returning = "ret", pointcut = "controllerWebLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
log.info("返回 : " + JSONObject.toJSONString(ret));
log.info("请求结束 : " + "********************************************");
}
}

posted @   勇敢-的心  阅读(154)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示