zoukankan      html  css  js  c++  java
  • 使用AOP统一处理日志

    依赖导入

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

    自定义日志注解

    package com.mylog.log;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface BaseDataLog {
        String name() default "";
    }
    

    切面类

    @Slf4j
    @Aspect
    @Component
    public class BaseDataLogAspect {
        @Pointcut("@annotation(com.mylog.log.BaseDataLog)")
        public void fillPointcut(){
            // empty
        }
        @Around("fillPointcut()")
        public Object around(ProceedingJoinPoint joinPoint){
            long startTime = System.currentTimeMillis();
            String startTimeString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime);
            Object[] args = joinPoint.getArgs();
            /**
             * 获取注解的值(服务名)
             */
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            BaseDataLog entityFieldStuffer = signature.getMethod().getAnnotation(BaseDataLog.class);
            String serviceName = entityFieldStuffer.name();
            String className = joinPoint.getSignature().getDeclaringTypeName();
            String methodName = joinPoint.getSignature().getName();
            StringBuilder serviceParam = new StringBuilder();
            for(Object param : args){
                serviceParam.append(param.toString());
            }
    
            // 执行源方法
            Object result = null;
            try{
                result = joinPoint.proceed();
            }catch (AppException e){
                if (e.getCause() != null) {
                    throw new BusinessException(e.getCode(),e.getMessage(),e.getCause());
                } else {
                    throw new BusinessException(e.getCode(),e.getMessage());
                }
    
            } catch (Throwable throwable) {
                log.error(throwable.getMessage());
            }
    
            long respTime = System.currentTimeMillis() - startTime;
            log.info("操作时间:{},请求:{},类名:{},方法名:{},输入参数:{},操作执行时长:{}",
                    startTimeString,serviceName,className,methodName,serviceParam.toString(),respTime);
    
            return result;
        }
    
    }
    

    使用

    在要使用的方法上打上@BaseDataLog(name = "方法名")注解即可
    
  • 相关阅读:
    MySQL数据库优化【笔记】_索引的创建和删除(ALTER TABLE方式)
    [C#基础知识]泛型Dictionary<string,string>的用法详解
    权重衰退
    softmax回归
    交叉熵损失函数
    线性回归
    极大似然估计
    【SpringBoot-消息 02】
    【SpringBoot-cache 01】
    【JavaWeb 实际项目_Cookie&Session 06】
  • 原文地址:https://www.cnblogs.com/Wangddongyu235/p/13782607.html
Copyright © 2011-2022 走看看