自学内容网 自学内容网

springboot使用AOP做接口调用日志记录

引入依赖

<!--aop-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

自定义注解

/**
 * 自定义注解
 * @date 2024-12-03
 * @author yuguiming
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface InterfaceLogAnnotation {

    /**
     * 接口名称
     */
    String interfaceName();

    /**
     * 系统来源
     */
    String systemSource();

}

要记录的方法上加注解

    
    @PostMapping(value = "/role")
    @Operation(summary = "同步角色信息")
    @InterfaceLogAnnotation(interfaceName = "同步角色信息", systemSource = "IAM")
    public IamResultVo role(@RequestBody RoleDto roleDto) {
        if (!ObjectUtils.isEmpty(roleDto)) {
            try {
                iamSyncRoleService.saveSyncRole(roleDto);
                return new IamResultVo();
            } catch (Exception e) {
                log.error("同步角色出错,{}", e);
                return new IamResultVo(e.getMessage());
            }
        }
        return new IamResultVo("推送数据为空");
    }

aop拦截


import com.alibaba.fastjson.JSONObject;
import com.zbom.module.user.vo.UserVo;
import com.zbom.user.module.log.entity.PgInterfaceLog;
import com.zbom.user.module.log.service.PgInterfaceLogService;
import com.zbom.web.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.zbom.user.aop.annotation.InterfaceLogAnnotation;
import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class LogAop {

    @Autowired
    private PgInterfaceLogService pgInterfaceLogService;

    @Around("@annotation(com.zbom.user.aop.annotation.InterfaceLogAnnotation)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            //获取开始时间
            long begin = System.currentTimeMillis();
            //获取方法对象
            Signature sig = joinPoint.getSignature();
            MethodSignature mSig = (MethodSignature)sig;
            Method method = mSig.getMethod();
            InterfaceLogAnnotation ann = method.getAnnotation(InterfaceLogAnnotation.class);
            //获取操作结束时间
            long end = System.currentTimeMillis()-begin;
            PgInterfaceLog interfaceLog = new PgInterfaceLog();
            //系统来源
            interfaceLog.setSystemSource(ann.systemSource());
            //方法名称
            interfaceLog.setInterfaceName(ann.interfaceName());
            //方法参数
            String param = JSONObject.toJSONString(joinPoint.getArgs());
            interfaceLog.setRequestParam(param);
            //方法返回值
            Object result = joinPoint.proceed();
            String returnValue = JSONObject.toJSONString(result);
            interfaceLog.setResponseParam(returnValue);
            //状态
            JSONObject jsonObject = JSONObject.parseObject(interfaceLog.getResponseParam());
            String code = jsonObject.getString("code");
            interfaceLog.setReturnStatus((!StringUtils.isBlank(code) || (!"200".equals(code) || "0".equals(code))) ? 0 : 1);
            //创建人
            UserVo userVo = UserUtil.getUser();
            interfaceLog.setCreateUser(userVo.getId());
            interfaceLog.setCreateUserName(userVo.getUserAccount()+"("+userVo.getUserRealName()+")");
            //耗时
            double second = (double)end/1000;
            interfaceLog.setInvokeTime(String.valueOf(second));
            log.error("interfaceLog:{}",interfaceLog);
            pgInterfaceLogService.save(interfaceLog);
        }catch (Exception e){
            log.error("aop保存日志异常:{}",e.getMessage());
        }
        return joinPoint.proceed();
    }

}


原文地址:https://blog.csdn.net/Ming13416908424/article/details/144249180

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!