Springboot使用MethodInterceptor和切面统一打印service层信息

该博客介绍了如何使用Spring AOP和AspectJ表达式来定义一个切点,通过`ServiceInterceptor`方法拦截器捕获并处理服务层异常。当发生异常时,根据异常类型和错误代码进行不同级别的日志记录,包括业务异常、警告和错误信息,并提供了自定义的`ServiceException`来封装异常信息。
package org.example.interc;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ServiceInterceptor implements MethodInterceptor {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public ServiceInterceptor() {
    }

    public Object invoke(MethodInvocation invocation) throws Throwable {
        long startTimeMillis = System.currentTimeMillis();
        long endTimeMillis = 0L;
        String className = invocation.getThis().getClass().getSimpleName();
        String interfaceFullName = invocation.getThis().getClass().getName();
        String methodName = invocation.getMethod().getName();
        String txName = "交易:" + className + "." + methodName;

        try {
            Class<?>[] interfaces = invocation.getThis().getClass().getInterfaces();
            if (interfaces != null && interfaces.length > 0) {
                interfaceFullName = interfaces[0].getName();
            }
        } catch (Exception var15) {
            this.logger.warn("获取接口名称异常", var15);
        }

        Object[] args = invocation.getArguments();
        boolean noArgs = false;
        if (args == null || args.length < 1 || args[0] == null) {
            noArgs = true;
        }

        try {
            if (!noArgs) {
                CheckInputUtil.validate(args[0]);
            }

            Object returnObj = invocation.proceed();
            endTimeMillis = System.currentTimeMillis();
            this.logger.info(txName + " success ,耗时:" + (endTimeMillis - startTimeMillis) + "ms");
            return returnObj;
        } catch (Exception var16) {
            endTimeMillis = System.currentTimeMillis();
            if (var16 instanceof ServiceException) {
                ServiceException serE = (ServiceException) var16;
                if (StringUtils.length(serE.getCode()) < 10) {
                    this.logger.error("业务异常:" + serE.getExtMsg(), serE);
                    this.logger.info(txName + " failure ,耗时:" + (endTimeMillis - startTimeMillis) + "ms");
                } else {
                    String logLevel = serE.getCode().substring(5, 6);
                    if ("E".equals(logLevel)) {
                        this.logger.error("业务异常:" + serE.getExtMsg(), serE);
                        this.logger.info(txName + " failure ,耗时:" + (endTimeMillis - startTimeMillis) + "ms");
                    } else i
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值