使用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 = "方法名")注解即可
posted @ 2020-10-08 20:31  DDDDy  阅读(156)  评论(0编辑  收藏  举报