Spring AOP+注解方式实现系统日志记录

一、前言

execution表达式详解:https://blog.csdn.net/qq_41460654/article/details/119637891

在上篇文章中,我们使用了AOP思想实现日志记录的功能,代码中采用了指定连接点方式(@Pointcut(“execution(* com.nowcoder.community.controller..(…))”)),指定后不需要在进行任何操作就可以记录日志了,但是如果我们对某些controller不想记录日志,就需要更改指定的切点,灵活性较差。因此采用注解+AOP方式,实现更灵活的日志记录功能。

二、注解实现代码
package com.nowcoder.community.annotation;

import java.lang.annotation.*;

/**
 * @author Janson
 * @Description AOP日志记录注解
 * @Date 2023/5/12
 * @Target LogAspect 注解的作用目标
 * @Retention 指定注解的保留时间
 */

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAspect {
    
    /**
     * title 自定义名称
     * description 自定义描述
     * @return
     */
    String title() default "";
    
    String description() default "";
}

三、AOP日志记录类实现代码

定义切点(织入点)
execution(* com.nowcoder.community.controller..(…))
- 第一个 * 表示 支持任意类型返回值的方法
- com.nowcoder.community.controller 表示这个包下的类
- 第二个 * 表示 controller包下的任意类
- 第三个 * 表示 类中的任意方法
- (…) 表示方法可以拥有任意参数
可以根据自己的需求替换。
不同之处:controller后两个 “. .”,表示controller包及任意子包均匹配。
execution(* com.nowcoder.community.controller….(…))

package com.nowcoder.community.aspect;

import com.nowcoder.community.annotation.LogAspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author Janson
 * @Description AOP日志记录,此方案不统一设置连接点 @Pointcut,而是采用注解方式,指定连接的方法
 * @Date 2023/5/12
 */
@Aspect
@Component
public class LogAspectAnnotationTest {
    
    /**
     * 定义切点(织入点)
     *  execution(* com.nowcoder.community.controller.*.*(..))
     *      - 第一个 * 表示 支持任意类型返回值的方法
     *      - com.nowcoder.community.controller 表示这个包下的类
     *      - 第二个 * 表示 controller包下的任意类
     *      - 第三个 * 表示 类中的任意方法
     *      - (..) 表示方法可以拥有任意参数
     *   可以根据自己的需求替换。
     *
     */
    
    @Before(value = "@annotation(controllerLog)")
    public void before(JoinPoint joinPoint, LogAspect controllerLog){
    
        String className = joinPoint.getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null){
            return;
        }
        String ip = attributes.getRequest().getRemoteHost();
        String requestURI = attributes.getRequest().getRequestURI();
        String requestMethod = attributes.getRequest().getMethod();
        String title = controllerLog.title();
        String description = controllerLog.description();
        System.out.println("title is " + title + ",description is " + description);
        System.out.println("before excute ······");
        System.out.println(String.format("用户: [%s] 的请求路径为:[%s], 请求方式为: [%s],请求类名为: [%s], 请求方法名为: [%s]", ip,requestURI,
                                         requestMethod,className,methodName));
    }
    
    @After(value = "@annotation(controllerLog)")
    public void after(JoinPoint joinPoint, LogAspect controllerLog){
        
        String className = joinPoint.getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null){
            return;
        }
        String ip = attributes.getRequest().getRemoteHost();
        String requestURI = attributes.getRequest().getRequestURI();
        String requestMethod = attributes.getRequest().getMethod();
        String title = controllerLog.title();
        String description = controllerLog.description();
        System.out.println("title is " + title + ",description is " + description);
        System.out.println("after excute ······");
        System.out.println(String.format("用户: [%s] 的请求路径为:[%s], 请求方式为: [%s],请求类名为: [%s], 请求方法名为: [%s]", ip,requestURI,
                                         requestMethod,className,methodName));
    }
    
    @AfterReturning(value = "@annotation(controllerLog)")
    public void afterReturning(JoinPoint joinPoint, LogAspect controllerLog){
        
        String className = joinPoint.getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null){
            return;
        }
        String ip = attributes.getRequest().getRemoteHost();
        String requestURI = attributes.getRequest().getRequestURI();
        String requestMethod = attributes.getRequest().getMethod();
        String title = controllerLog.title();
        String description = controllerLog.description();
        System.out.println("title is " + title + ",description is " + description);
        System.out.println("afterReturning excute ······");
        System.out.println(String.format("用户: [%s] 的请求路径为:[%s], 请求方式为: [%s],请求类名为: [%s], 请求方法名为: [%s]", ip,requestURI,
                                         requestMethod,className,methodName));
    }
    
    @AfterThrowing(value = "@annotation(controllerLog)",throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, LogAspect controllerLog,Exception e){
        
        String className = joinPoint.getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null){
            return;
        }
        String ip = attributes.getRequest().getRemoteHost();
        String requestURI = attributes.getRequest().getRequestURI();
        String requestMethod = attributes.getRequest().getMethod();
        String title = controllerLog.title();
        String description = controllerLog.description();
        System.out.println("title is " + title + ",description is " + description);
        System.out.println("afterThrowing excute ······" + e.getMessage());
        System.out.println(String.format("用户: [%s] 的请求路径为:[%s], 请求方式为: [%s],请求类名为: [%s], 请求方法名为: [%s],请求失败原因: [%s]", ip,
                                         requestURI, requestMethod,className,methodName,e.getMessage()));
    }
    
    @Around(value = "@annotation(controllerLog)")
    public void around(ProceedingJoinPoint joinPoint, LogAspect controllerLog) throws Throwable {
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        System.out.println("className is : " + className + ". methodName is : " + methodName);
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (attributes == null){
            return;
        }
        // 请求ip
        String ip = attributes.getRequest().getRemoteHost();
        // 请求路径
        String requestURI = attributes.getRequest().getRequestURI();
        // 请求方法
        String requestMethod = attributes.getRequest().getMethod();
        String title = controllerLog.title();
        String description = controllerLog.description();
        
        System.out.println(String.format("用户: [%s] 的请求路径为:[%s], 请求方式为: [%s],请求类名为: [%s], 请求方法名为: [%s]", ip,requestURI,
                                         requestMethod,className,methodName));
        Object obj = null;
        try {
            obj = joinPoint.proceed();
        } catch (Throwable e) {
            System.out.println("我捕获了异常");
            throw new RuntimeException("执行失败",e);
        }
        System.out.println(String.format("用户: [%s] 的请求路径为:[%s], 请求方式为: [%s],请求类名为: [%s], 请求方法名为: [%s]", ip,requestURI,
                                         requestMethod,className,methodName));
        System.out.println("around excute after ········");
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring AOP是一种利用代理机制实现面向切面编程的框架。它可以通过自定义注解实现一些特定的逻辑。在Spring AOP中,我们可以通过在自定义注解上添加相关的切点表达式和通知方法来实现对目标方法的增强。这样可以实现一些横切关注点的统一处理,如记录系统日志、权限校验等。通过使用Spring AOP和自定义注解,我们可以更加灵活地对代码进行管理和维护。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [spring aop 自定义注解保存操作日志到mysql数据库 源码](https://download.csdn.net/download/y_h_d/48993109)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Spring AOP 自定义注解实现代码](https://download.csdn.net/download/weixin_38714637/12781779)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [spring AOP自定义注解方式实现日志管理的实例讲解](https://download.csdn.net/download/weixin_38552536/12764634)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Janson666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值