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 = "方法名")注解即可
    
  • 相关阅读:
    Django + uWSGI + Nginx 实现生产环境部署
    面试题(一)
    Python基础之路
    Tornado之实例和扩展
    Scrapy源码研究前戏
    算法之基本概念
    RedHat6.2系统安装ipvsadm+keepalived
    oracle11G 同时支持IPV4和IPV6配置
    redhat6.5 安装oracle11G
    python解析字体反爬
  • 原文地址:https://www.cnblogs.com/Wangddongyu235/p/13782607.html
Copyright © 2011-2022 走看看