SpringBoot使用aop切面做日志收集 、处理

  1. 在项目开发中,日志收集处理是一个必不可少的功能,会做日志收集处理的人很多,但是却没有比较详细的说明和注解支持小白去学习,于是,就诞生了这篇博客,可能这边博客也不是最好的,但我相信,对未来的大佬们来说,这个多少还是有点料的
  2. SpringBoot中做日志的方法有很多,比如用拦截器,在拦截器中进行处理需要进行收集日志的方法,同时也可以将日志存库,但是这种方法可能会有一个弊端,在拦截器中进行处理日志的话,对于请求量过大的系统,或者处理次数过多的,以及并发过高的项目来说,都是一个可怕的性能消耗。方法二,使用elk加kafka来做我们的日志,但是这种东西对于小白们来说,确实比较费劲,(我要是会用kafka还会是小白吗_)同时,对于小项目来说,使用kafka的成本太高(不是经济成本哦!),所以杀鸡用牛刀,太浪费了。方法三,使用aop做切面,实现日志的收集处理,(也就是本篇文章的get点了)
  3. aop做日志处理的关键原因,量级小,简单,适合小型项目且并发量不是特别大的(对于如何使用aop可以去看博主的其他博客,里面有aop注解使用的详细介绍和使用方法)aop实现原理
  4. 各位新星们,下面上大菜了!
  5. 需要使用aop的话,我们需要引入aop的jar包,(怎么引入就不告诉你,这是武功秘籍,3元一本,欢迎选购!)
<dependency>
	<groupId>org.springfarmework.boot</groupId>
	<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

够意思吧,这都能给你写出来,你要问我放在哪,我小声告诉你,放到pom文件里面哦!
6. 引入完成jar包之后,需要去我们的配置文件中进行开启aop注解支持,否则的话,你的注解是不管用的

spring:
  #切面启用
  aop:
    proxy-target-class: true		#默认为false
    auto: true		#默认为false

proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。首先说明下proxy-target-class="true"和proxy-target-class="false"的区别,为true则是基于类的代理将起作用(需要cglib库),为false或者省略这个属性,则标准的JDK 基于接口的代理将起作用。
proxy-target-class在spring事务、aop、缓存这几块都有设置,其作用都是一样的。
auto为开启aop注解,如同SpringBoot的自动配置一般
7. 开启注解支持后,我们就可以开始进行个人秀了!
8. 我们可以自定义一个注解,通过注解实现我们都controller或者service的日志收集
controller的自定义注解,对于如何使用SpringBoot的自定义注解以及如何定义可以查看博主的其他博客

package cn.annotation;
 
import java.lang.annotation.*;
 
/**
 * @version V1.0
 * Description:  自定义注解,拦截controller
 */
 
@Target({ElementType.PARAMETER, ElementType.METHOD})//作用在参数和方法上
@Retention(RetentionPolicy.RUNTIME)//运行时注解
@Documented//表明这个注解应该被 javadoc工具记录
public @interface SystemControllerLog {
    String description() default "";
}

service的自定义注解

package cn.annotation;
 
import java.lang.annotation.*;
 
/**
 * @version V1.0
 * Description:  自定义注解,拦截service
 */
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemServiceLog {
    String description() default "";
}
  1. 这里就需要去写aop的切面类了
package cn.annotation;
 
import cn.pojo.Action;
import cn.pojo.User;
import cn.service.ActionService;
import cn.utils.IpUtils;
import cn.utils.JsonUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
 
/**
 * Title: SystemControllerLog
 * @date 2018年8月31日
 * @version V1.0
 * Description: 切点类
 */
@Aspect
@Component
@SuppressWarnings("all")
public class SystemLogAspect {
    //注入Service用于把日志保存数据库,实际项目入库采用队列做异步
    @Resource
    private ActionService actionService;
    //本地异常日志记录对象
    private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);
    //Service层切点
    @Pointcut("@annotation(cn.annotation.SystemServiceLog)")
    public void serviceAspect(){
    }
 
    //Controller层切点
    @Pointcut("@annotation(cn.oa.annotation.SystemControllerLog)")
    public void controllerAspect(){
    }
 
    /**
     * @Description  前置通知  用于拦截Controller层记录用户的操作
     */
 
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        //读取session中的用户,需要在请求同中携带用户的信息才能获取到数据,博主的token使用中有介绍如何携带使用
        //User user = (User) session.getAttribute("user");
        try {
            System.out.println("==============前置通知开始==============");
            System.out.println("请求方法" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()));
            System.out.println("方法描述:" + getControllerMethodDescription(joinPoint));
           // System.out.println("请求人:"+user.getUsername());
            //*========数据库日志=========*//
            //保存数据库(这里可以直接调用service将收集到的日志信息存到数据库中)
        }catch (Exception e){
            //记录本地异常日志
            logger.error("==前置通知异常==");
            logger.error("异常信息:{}",e.getMessage());
        }
    }
 
    /**
     * @Description  异常通知 用于拦截service层记录异常日志
     */
    @AfterThrowing(pointcut = "serviceAspect()",throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint,Throwable e){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        //读取session中的用户
        User user = (User) session.getAttribute("user");
        //获取用户请求方法的参数并序列化为JSON格式字符串
        String params = "";
        if (joinPoint.getArgs()!=null&&joinPoint.getArgs().length>0){
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                params+= JsonUtils.objectToJson(joinPoint.getArgs()[i])+";";
            }
        }
        try{
            System.out.println("异常代码:" + e.getClass().getName());
            System.out.println("异常信息:" + e.getMessage());
            System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
            System.out.println("方法描述:" + getServiceMethodDescription(joinPoint));
            System.out.println("请求人:" + user.getUsername());
            System.out.println("请求IP:" + ip);
            System.out.println("请求参数:" + params);
            Action action = new Action();
            action.setActionDes(getServiceMethodDescription(joinPoint));
            action.setActionType("1");
            action.setUserId(user.getId());
            action.setActionIp(ip);
            action.setActionTime(new Date());
            //保存到数据库
            actionService.add(action);
        }catch (Exception ex){
            //记录本地异常日志
            logger.error("==异常通知异常==");
            logger.error("异常信息:{}", ex.getMessage());
        }
    }
 
 
    /**
     * @Description  获取注解中对方法的描述信息 用于service层注解
     */
    public static String getServiceMethodDescription(JoinPoint joinPoint)throws Exception{
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
		Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method:methods) {
            if (method.getName().equals(methodName)){
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length==arguments.length){
                    description = method.getAnnotation(SystemServiceLog.class).description();
                    break;
                }
            }
        }
        return description;
    }
 
 
 
    /**
     * @Description  获取注解中对方法的描述信息 用于Controller层注解
     */
    public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();//目标方法名
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method:methods) {
            if (method.getName().equals(methodName)){
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length==arguments.length){
                    description = method.getAnnotation(SystemControllerLog.class).description();
                    break;
                }
            }
        }
        return description;
    }
}

这里有两个工具类是获取ip和进行json格式转换的,大家注意一下哦
10. 到这里我们的aop就已经完成了,需要使用就的话就在你需要的controller或service中进行添加我们自己定义的注解就行了

@SystemControllerLog(description = "")
注解加在控制器中方法上面,括号里写上操作描述
@SystemServiceLog(description = "")
注解加在service层方法上面,括号里写上操作描述

这个博客也是博主去找了一些资料,然后通过自己使用进行修改后出来的一个demo,是个人的片面理解,如果不到的地方,欢迎批评指正
参考博客参考的他人博客

转载记得加我的来源哦 !

  • 11
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值