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 = "方法名")注解即可
    
  • 相关阅读:
    POJ 3468 区间更新,区间求和(经典)
    HDU 1698 区间更新
    POJ 2828 单点更新(好题)
    HDU 2795 单点更新,区间优先查找(想法)
    HDU 1394 树状数组求逆序对
    HDU 1754 单点更新,求区间最大值
    Servlet 3.0 对异步处理的支持
    Servet3.0于Servlet2.5比较
    你的灯还亮着吗读书笔记3
    你的灯还亮着吗读书笔记2
  • 原文地址:https://www.cnblogs.com/Wangddongyu235/p/13782607.html
Copyright © 2011-2022 走看看