定义一个切面日志

spring 文章 2024-03-25 10:11 430 0 全屏看文

AI助手支持GPT4.0

我们可以通过aspect进行无侵入式的日志记录,

具体代码如下:

定义一个注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogOperation {
    String value() default "";
}

我们定义一个切面处理类。

并定义切面,然后,通过@Around("logPointCut()")注解,你定义了一个环绕通知(Around Advice),它将围绕着上述切点定义的方法执行。这意味着,每当有方法被@LogOperation注解标记,并被调用时,around方法就会被触发。在这个方法内部,你可以在目标方法执行前后添加自定义逻辑,比如记录日志、计算执行时间等。

/**
* 系统⽇志,切⾯处理类
*/
@Aspect
@Component
public class LogOperationAspect {
    @Autowired
    private SysLogOperationService sysLogOperationService;
    
    @Pointcut("@annotation(cn.sanshu.common.annotation.LogOperation)")
    public void logPointCut() {
        
   }
    
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        try {
            //执⾏⽅法
            Object result = point.proceed();
            
            //执⾏时⻓(毫秒)
            long time = System.currentTimeMillis() - beginTime;
            //保存⽇志
            saveLog(point, time, OperationStatusEnum.SUCCESS.value());
            
            return result;
       }catch(Exception e) {
            //执⾏时⻓(毫秒)
            long time = System.currentTimeMillis() - beginTime;
            //保存⽇志
            saveLog(point, time, OperationStatusEnum.FAIL.value());
            
            throw e;
       }
   }
    
    private void saveLog(ProceedingJoinPoint joinPoint, long time,
Integer status) {
        //逻辑对象处理
        
        //保存到DB
        sysLogOperationService.save(log);
   }
}


使用:

image.png

-EOF-

AI助手支持GPT4.0


国内超级便宜服务器

摸鱼人热门新闻聚合

钻级赞助商 我要加入

开发者在线工具

第三方支付技术请加QQ群

相关文章
java一行代码判断2个数组里是否有相同的值
spring里使用静态方法获取HttpServeltRequest
所有spring的bean都初始化完成,然后在执行某一方法
springJdbcTemplate 执行 sql中包含in的用法
spring项目输出当前的activeprofile
随便看看
教育科技公司申请微信支付被拒绝? 4696
微信公众号免300认证教程 5777
小程序已经上线,作为管理员无法在小程序数据助手查看数据? 5188
小程序广告组件通过审核,但是小程序内没有显示广告? 4963
企业微信通讯录账号被管理员误/恶意删除,怎么办? 9391
问题? 8912
如何快速搭建抽奖助手小程序(无需代码知识) 6042
许涛 大哥在吗, 要解冻小程序的时候提示信息主体不一致, 能帮忙看下吗? 7346
小程序搜一搜全称搜索不显示 麻烦解决一下!谢谢 6671
我的小程序广告收款主体是个体工商户,每个月邮寄两次发票很是麻烦,我年底的时候打包邮寄一次可以么? 6000