SpringBoot基于AOP 做个操作日志~!

前言

Spring系列都很熟悉了,AOP IOC等概念都耳熟能详了,但AOP使用的真的不多,实践出真知,写个操作日志,记录每一个请求,方便问题追溯,也为系统性能提升提供可靠的数据分析依据。

实现方式

1. 先写个自定义注解
import java.lang.annotation.*;

/**
 * Description:
 * 接口调用日志自定义注解
 * <p>
 * ClassName: CallLog
 * date: 2021/1/11 11:18
 *
 * @author jo.li
 * @version 1.0
 * @since JDK 1.8
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CallLog {
    String callModule() default "";
    String callType() default "";
    String callDesc() default "";
}
  1. Target: 指明了修饰的这个注解的使用范围,即被描述的注解可以用在哪里。
    参数说明
    TYPE:类,接口或者枚举
    FIELD:域,包含枚举常量
    METHOD:方法
    PARAMETER:参数
    CONSTRUCTOR:构造方法
    LOCAL_VARIABLE:局部变量
    ANNOTATION_TYPE:注解类型
    PACKAGE:包
  2. Retention:指明修饰的注解的生存周期,即会保留到哪个阶段。
    SOURCE:源码级别保留,编译后即丢弃。
    CLASS:编译级别保留,编译后的class文件中存在,在jvm运行时丢弃,这是默认值。
    RUNTIME: 运行级别保留,编译后的class文件中存在,在jvm运行时保留,可以被反射调用。
  3. Documented:指明修饰的注解,可以被例如javadoc此类的工具文档化,只负责标记,没有成员取值。
2. AOP的切面 搞里头~!
import com.alibaba.fastjson.JSON;
import com.assistant.audio.utils.DateUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * 接口调用日志自定义注解实现Aop切面
 * <p>
 * ClassName: CallLogAspect
 * date: 2021/1/11 12:55
 *
 * @author jo.li
 * @version 1.0
 * @since JDK 1.8
 */
@Aspect
@Component
public class CallLogAspect {

    /**
     * Description: <br/>
     * 调用日志切入点,记录调用日志在注解的位置切入代码
     * callLogPointCut <br/>
     * Date 2021/1/11 12:57
     *
     * @return: void
     * @author jo.li
     **/
    @Pointcut("@annotation(com.assistant.audio.log.CallLog)")
    public void callLogPointCut() {

    }

    @Pointcut("execution(* com.assistant.audio.api.controller..*.*(..))")
    public void callExceptionLogPointCut() {

    }

    /**
     * Description: <br/>
     * 正常返回通知,拦截调用日志,连接点正常执行完成后执行,如果连接点异常则不会执行
     * saveCallLog <br/>
     * Date 2021/1/11 13:00
     *
     * @param joinPoint:
     * @param keys:
     * @return: void
     * @author jo.li
     **/
    @AfterReturning(value = "callLogPointCut()", returning = "keys")
    public void saveCallLog(JoinPoint joinPoint, Object keys) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        try {

            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取操作
            CallLog opLog = method.getAnnotation(CallLog.class);
            if (opLog != null) {
                String operModul = opLog.callModule();
                String operType = opLog.callType();
                String operDesc = opLog.callDesc();
                // 操作模块
                System.out.println(operModul);
                // 操作类型
                System.out.println(operType);
                // 操作描述
                System.out.println(operDesc);
            }
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            // 请求方法
            System.out.println(methodName);

            // 请求的参数
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 将参数所在的数组转换成json
            String params = JSON.toJSONString(rtnMap);
            // 请求参数
            System.out.println(params);
            // 返回结果
            System.out.println(JSON.toJSONString(keys));
            // 请求URI
            System.out.println(request.getRequestURI());
            // 创建时间
            System.out.println(DateUtil.getNowTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 转换request 请求参数
     *
     * @param paramMap request获取的参数数组
     */
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<>(16);
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }

    /**
     * 异常返回通知,用于拦截异常日志信息 连接点抛出异常后执行
     *
     * @param joinPoint 切入点
     * @param e         异常信息
     */
    @AfterThrowing(pointcut = "callExceptionLogPointCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            // 请求的参数
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 将参数所在的数组转换成json
            String params = JSON.toJSONString(rtnMap);
            System.out.println(params);
            System.out.println(methodName);
            System.out.println(e.getClass().getName());
            System.out.println(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));
            System.out.println(request.getRequestURI());
            System.out.println(DateUtil.getNowTime());
        } catch (Exception e2) {
            e2.printStackTrace();
        }

    }

    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }
}
  1. 以上代码只是输出到控制台,有条件的可以数据库建表,然后存储到数据库里。
  2. 以上代码日志输出分成了两部分,正常操作日志和异常日志,随手写的,如果使用还需要详细测试并根据实际业务进行修改。
3. 使用
// 在需要记录的方法上面加上注解就完事了
@CallLog(callModule = "模块",callType = "类型",callDesc = "备注")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

暴躁码农

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

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

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

打赏作者

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

抵扣说明:

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

余额充值