写个日志请求切面,前后端甩锅更方便

一、切面介绍

面向切面编程是一种编程范式,它作为OOP面向对象编程的一种补充,用于处理系统中分布于各个模块的横切关注点,比如事务管理、权限控制、缓存控制、日志打印等等。
AOP把软件的功能模块分为两个部分:核心关注点和横切关注点。业务处理的主要功能为核心关注点,而非核心、需要拓展的功能为横切关注点。AOP的作用在于分离系统中的各种关注点,将核心关注点和横切关注点进行分离,使用切面有以下好处:
(1)集中处理某一关注点/横切逻辑
(2)可以很方便的添加/删除关注点
(3)侵入性少,增强代码可读性及可维护性
因此当想打印请求日志时很容易想到切面,对控制层代码0侵入

切面的使用【基于注解】
@Aspect => 声明该类为一个注解类

切点注解:
@Pointcut => 定义一个切点,可以简化代码

通知注解:
@Before => 在切点之前执行代码
@After => 在切点之后执行代码
@AfterReturning => 切点返回内容后执行代码,可以对切点的返回值进行封装
@AfterThrowing => 切点抛出异常后执行
@Around => 环绕,在切点前后执行代码

二、动手写一个请求日志切面

1.使用@Pointcut定义切点

@Pointcut("execution(* your_package.controller..*(..))")
public void requestServer() {
}

@Pointcut定义了一个切点,因为是请求日志切边,因此切点定义的是Controller包下的所有类下的方法。定义切点以后在通知注解中直接使用requestServer方法名就可以了。

2.使用@Before再切点前执行

@Before("requestServer()")
public void doBefore(JoinPoint joinPoint) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) 
    RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    LOGGER.info("===============================Start========================");
    LOGGER.info("IP                 : {}", request.getRemoteAddr());
    LOGGER.info("URL                : {}", request.getRequestURL().toString());
    LOGGER.info("HTTP Method        : {}", request.getMethod());
    LOGGER.info("Class Method       : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
}

在进入Controller方法前,打印出调用方IP、请求URL、HTTP请求类型、调用的方法名。

3.使用@Around打印进入控制层的入参

@Around("requestServer()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    long start = System.currentTimeMillis();
    Object result = proceedingJoinPoint.proceed();
    LOGGER.info("Request Params       : {}", getRequestParams(proceedingJoinPoint));
    LOGGER.info("Result               : {}", result);
    LOGGER.info("Time Cost            : {} ms", System.currentTimeMillis() - start);

    return result;
}

打印了入参、结果以及耗时。

4.getRquestParams方法

private Map<String, Object> getRequestParams(ProceedingJoinPoint proceedingJoinPoint) {
     Map<String, Object> requestParams = new HashMap<>();

      //参数名
     String[] paramNames = ((MethodSignature)proceedingJoinPoint.getSignature()).getParameterNames();
     //参数值
     Object[] paramValues = proceedingJoinPoint.getArgs();

     for (int i = 0; i < paramNames.length; i++) {
         Object value = paramValues[i];

         //如果是文件对象
         if (value instanceof MultipartFile) {
             MultipartFile file = (MultipartFile) value;
             value = file.getOriginalFilename();  //获取文件名
         }

         requestParams.put(paramNames[i], value);
     }

     return requestParams;
 }

通过 @PathVariable以及@RequestParam注解传递的参数无法打印出参数名,因此需要手动拼接一下参数名,同时对文件对象进行了特殊处理,只需获取文件名即可。

5.@After方法调用后执行

@After("requestServer()")
public void doAfter(JoinPoint joinPoint) {
    LOGGER.info("===============================End========================");
}

没有业务逻辑只是打印了End

6.完整切面代码

@Component
@Aspect
public class RequestLogAspect {
    private final static Logger LOGGER = LoggerFactory.getLogger(RequestLogAspect.class);

    @Pointcut("execution(* your_package.controller..*(..))")
    public void requestServer() {
    }

    @Before("requestServer()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) 
RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        LOGGER.info("===============================Start========================");
        LOGGER.info("IP                 : {}", request.getRemoteAddr());
        LOGGER.info("URL                : {}", request.getRequestURL().toString());
        LOGGER.info("HTTP Method        : {}", request.getMethod());
        LOGGER.info("Class Method       : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), 
 joinPoint.getSignature().getName());
    }


    @Around("requestServer()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        LOGGER.info("Request Params     : {}", getRequestParams(proceedingJoinPoint));
        LOGGER.info("Result               : {}", result);
        LOGGER.info("Time Cost            : {} ms", System.currentTimeMillis() - start);

        return result;
    }

    @After("requestServer()")
    public void doAfter(JoinPoint joinPoint) {
        LOGGER.info("===============================End========================");
    }

    /**
     * 获取入参
     * @param proceedingJoinPoint
     *
     * @return
     * */
    private Map<String, Object> getRequestParams(ProceedingJoinPoint proceedingJoinPoint) {
        Map<String, Object> requestParams = new HashMap<>();

        //参数名
        String[] paramNames = 
((MethodSignature)proceedingJoinPoint.getSignature()).getParameterNames();
        //参数值
        Object[] paramValues = proceedingJoinPoint.getArgs();

        for (int i = 0; i < paramNames.length; i++) {
            Object value = paramValues[i];

            //如果是文件对象
            if (value instanceof MultipartFile) {
                MultipartFile file = (MultipartFile) value;
                value = file.getOriginalFilename();  //获取文件名
            }

            requestParams.put(paramNames[i], value);
        }

        return requestParams;
    }
}

三、切面日志类优化

每个信息都打印一行,在高并发请求下确实会出现请求之间打印日志串行的问题,因为测试阶段请求数量较少没有出现串行的情况,果然生产环境才是第一发展力,能够遇到更多bug,写更健壮的代码 解决日志串行的问题只要将多行打印信息合并为一行就可以了,因此构造一个对象。

1.RequestInfo.java

@Data
public class RequestInfo {
    private String ip;
    private String url;
    private String httpMethod;
    private String classMethod;
    private Object requestParams;
    private Object result;
    private Long timeCost;
}

2.环绕通知方法体

@Around("requestServer()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    long start = System.currentTimeMillis();
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    Object result = proceedingJoinPoint.proceed();
    
    RequestInfo requestInfo = new RequestInfo();            requestInfo.setIp(request.getRemoteAddr());
    requestInfo.setUrl(request.getRequestURL().toString());
    requestInfo.setHttpMethod(request.getMethod());
    requestInfo.setClassMethod(String.format("%s.%s", 

    proceedingJoinPoint.getSignature().getDeclaringTypeName(),
    proceedingJoinPoint.getSignature().getName()));
    
    requestInfo.setRequestParams(getRequestParamsByProceedingJoinPoint(proceedingJoinPoint));
    requestInfo.setResult(result);
    requestInfo.setTimeCost(System.currentTimeMillis() - start);
    LOGGER.info("Request Info      : {}", JSON.toJSONString(requestInfo));

    return result;
}

将url、http request这些信息组装成RequestInfo对象,再序列化打印对象
打印序列化对象结果而不是直接打印对象是因为序列化有更直观、更清晰。
在解决高并发下请求串行问题的同时添加了对异常请求信息的打印,通过使用 @AfterThrowing注解对抛出异常的方法进行处理。

3.RequestErrorInfo.java

@Data
public class RequestErrorInfo {
    private String ip;
    private String url;
    private String httpMethod;
    private String classMethod;
    private Object requestParams;
    private RuntimeException exception;
}

4.异常通知环绕体

@AfterThrowing(pointcut = "requestServer()", throwing = "e")
public void doAfterThrow(JoinPoint joinPoint, RuntimeException e) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
   
    RequestErrorInfo requestErrorInfo = new RequestErrorInfo();
    requestErrorInfo.setIp(request.getRemoteAddr());
    requestErrorInfo.setUrl(request.getRequestURL().toString());
    requestErrorInfo.setHttpMethod(request.getMethod());
    requestErrorInfo.setClassMethod(String.format("%s.%s", 

    joinPoint.getSignature().getDeclaringTypeName(),
    joinPoint.getSignature().getName()));
    
    requestErrorInfo.setRequestParams(getRequestParamsByJoinPoint(joinPoint));
    requestErrorInfo.setException(e);
    LOGGER.info("Error Request Info      : {}", JSON.toJSONString(requestErrorInfo));
}

对于异常,耗时是没有意义的,因此不统计耗时,而是添加了异常的打印。

5.完整日志请求切面代码:

@Component
@Aspect
public class RequestLogAspect {
    private final static Logger LOGGER = LoggerFactory.getLogger(RequestLogAspect.class);

    @Pointcut("execution(* your_package.controller..*(..))")
    public void requestServer() {
    }

    @Around("requestServer()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Object result = proceedingJoinPoint.proceed();
        
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setIp(request.getRemoteAddr());
        requestInfo.setUrl(request.getRequestURL().toString());
        requestInfo.setHttpMethod(request.getMethod());
        requestInfo.setClassMethod(String.format("%s.%s", proceedingJoinPoint.getSignature().getDeclaringTypeName(),
        
        proceedingJoinPoint.getSignature().getName()));
        
        requestInfo.setRequestParams(getRequestParamsByProceedingJoinPoint(proceedingJoinPoint));
        requestInfo.setResult(result);
        requestInfo.setTimeCost(System.currentTimeMillis() - start);
        LOGGER.info("Request Info      : {}", JSON.toJSONString(requestInfo));

        return result;
    }


    @AfterThrowing(pointcut = "requestServer()", throwing = "e")
    public void doAfterThrow(JoinPoint joinPoint, RuntimeException e) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
      
        HttpServletRequest request = attributes.getRequest();
        RequestErrorInfo requestErrorInfo = new RequestErrorInfo();
        requestErrorInfo.setIp(request.getRemoteAddr());
        requestErrorInfo.setUrl(request.getRequestURL().toString());
        requestErrorInfo.setHttpMethod(request.getMethod());
        requestErrorInfo.setClassMethod(String.format("%s.%s", 
       
        joinPoint.getSignature().getDeclaringTypeName(),
        joinPoint.getSignature().getName()));
        
        requestErrorInfo.setRequestParams(getRequestParamsByJoinPoint(joinPoint));
        requestErrorInfo.setException(e);
        LOGGER.info("Error Request Info      : {}", JSON.toJSONString(requestErrorInfo));
    }

    /**
     * 获取入参
     * @param proceedingJoinPoint
     *
     * @return
     * */
    private Map<String, Object> getRequestParamsByProceedingJoinPoint(ProceedingJoinPoint proceedingJoinPoint) {
        //参数名
        String[] paramNames = ((MethodSignature)proceedingJoinPoint.getSignature()).getParameterNames();
        //参数值
        Object[] paramValues = proceedingJoinPoint.getArgs();

        return buildRequestParam(paramNames, paramValues);
    }

    private Map<String, Object> getRequestParamsByJoinPoint(JoinPoint joinPoint) {
        //参数名
        String[] paramNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
        //参数值
        Object[] paramValues = joinPoint.getArgs();

        return buildRequestParam(paramNames, paramValues);
    }

    private Map<String, Object> buildRequestParam(String[] paramNames, Object[] paramValues) {
        Map<String, Object> requestParams = new HashMap<>();
        for (int i = 0; i < paramNames.length; i++) {
            Object value = paramValues[i];

            //如果是文件对象
            if (value instanceof MultipartFile) {
                MultipartFile file = (MultipartFile) value;
                value = file.getOriginalFilename();  //获取文件名
            }

            requestParams.put(paramNames[i], value);
        }

        return requestParams;
    }

    @Data
    public class RequestInfo {
        private String ip;
        private String url;
        private String httpMethod;
        private String classMethod;
        private Object requestParams;
        private Object result;
        private Long timeCost;
    }

    @Data
    public class RequestErrorInfo {
        private String ip;
        private String url;
        private String httpMethod;
        private String classMethod;
        private Object requestParams;
        private RuntimeException exception;
    }
}

四、项目中实际使用案例

import cn.jiguang.common.utils.StringUtils;
import com.xxx.core.utils.JsonUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @description 日志打印切面
 */

@Aspect
@Component
public class TaskLogAspect {


    @Pointcut("execution(public * com.xxx.service.task..*.*(..))" +
            "||execution(public * com.xxx.service.http..*.*(..))")
    public void log() { }


    @Around("log()")
    public Object doInvoke(ProceedingJoinPoint pjp) throws Throwable {
        final MethodSignature signature = (MethodSignature) pjp.getSignature();
        final String methodName = signature.getName();
        final String[] parameterNames = signature.getParameterNames();
        final String className = pjp.getTarget().getClass().getName();
        final LogDetail log = LogDetail.builder()
                .className(className)
                .methodName(methodName)
                .args(pjp.getArgs())
                .parameterName(parameterNames)
                .build();
        log.before();
        Object result = null;
        try {
            result = pjp.proceed();
            log.success(result);
        } catch (Exception e) {
            log.error(e);
        } finally {
            log.finish();
        }
        return result;
    }

    @Slf4j
    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    static class LogDetail{
        private String methodName;
        private String className;
        private Object[] args;
        private String[] parameterName;
        private Long start;
        private Map<String,Object> params = new HashMap<>();;
        public String toString(String stage){
            return this.toString(stage,"");
        }

        public  Map<String, Object> getParams() {
            this.params = new HashMap<>();
            for(int i = 0 ; i < parameterName.length ; i ++){
                this.params.put(parameterName[i],args[i] );
            }
            return this.params;
        }

        public String toString(String stage, String otherInfo){
            StringBuffer sb = new StringBuffer();
            sb.append("###").append(className).append("\t##").append(methodName);
            sb.append(":\t##").append(stage).append("\n");
            if(!MapUtils.isEmpty(getParams())){
                sb.append("\t\t### parameters : ").append(JsonUtils.object2Json(params)).append("\n");
            }
            if(!StringUtils.isEmpty(otherInfo)){
                sb.append("\t##").append("appendInfo:\n");
                sb.append("\t\t#").append(otherInfo).append("\n");
            }
            return sb.toString();
        }

        public void before() {
            this.start = System.currentTimeMillis();
            log.info(this.toString("start"));
        }
        public void success(Object result) {
            log.info(this.toString("success"));
        }
        public void error(Exception e) {
            log.error(this.toString("error",e.getMessage()));
        }
        public void finish() {
            Long time = System.currentTimeMillis() - this.start;
            String finish = "总耗时:"+ time;
            log.info(this.toString("finish",finish));
        }
    }
}

原文链接
https://juejin.cn/post/6844904087964614670#heading-3

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的示例代码,用于实现Spring Boot中的日志切面: 首先,我们需要定义一个切面类,并在其中编切面逻辑: ```java @Aspect @Component public class LoggingAspect { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Pointcut("execution(* com.example.controller..*.*(..))") public void controllerMethod() {} @Around("controllerMethod()") public Object logControllerMethodAccess(ProceedingJoinPoint joinPoint) throws Throwable { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String url = request.getRequestURL().toString(); String httpMethod = request.getMethod(); String remoteAddr = request.getRemoteAddr(); Object[] args = joinPoint.getArgs(); StringBuilder params = new StringBuilder(); for (Object arg : args) { params.append(arg.toString()).append(";"); } long startTime = System.currentTimeMillis(); Object result = joinPoint.proceed(); long endTime = System.currentTimeMillis(); logger.info("Request URL: {}, HTTP Method: {}, Remote Address: {}, Parameters: {}, Response Time: {} ms", url, httpMethod, remoteAddr, params.toString(), endTime - startTime); return result; } } ``` 上述代码中,我们使用了`@Aspect`注解来标识这是一个切面类,并使用`@Component`注解将其声明为Spring Bean。接着,我们定义了一个切点`controllerMethod()`,用于匹配所有Controller类中的方法。最后,我们在`controllerMethod()`切点上使用了`@Around`注解,表示这是一个环绕通知,即在Controller方法执行前后都会执行。 在`@Around`注解中,我们首先获取了请求的URL、HTTP Method和远程地址等信息,然后将请求参数转换为字符串,并在执行Controller方法前记录当前时间。在Controller方法执行完成后,我们再记录当前时间并计算出响应时间,最后将所有信息以日志的形式输出到控制台中。 最后,我们需要在Spring Boot的配置文件中开启AOP: ```yaml spring: application: name: demo aop: auto: true ``` 这样,当我们启动Spring Boot应用时,就能够看到所有Controller方法的访问信息被打印在控制台中了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值