Springboot日志记录请求切面

 打印接口url、入参、调用时间

@Aspect
@Order(1)
@Component
@Slf4j
public class LogAspect {
    @Pointcut("execution(public * com.xxx.controller.*.*(..)))")
    public void timePointCut() {
    }

    @Around("timePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String url = request.getServletPath();
        String params = getRequestParams(request, point, true);
        long beginTime = System.currentTimeMillis();
        Object object = point.proceed();
        log.info("接口调用:url:{}, params:{}, totalTime:{}", url, params, (System.currentTimeMillis() - beginTime));
        return object;
    }
}

/**
     * @param request:   request
     * @param joinPoint: joinPoint
     * @param isFilter:  是否过滤太长的
     * @Description: 获取请求参数
     */
    public static String getRequestParams(HttpServletRequest request, JoinPoint joinPoint, boolean isFilter) {
        String httpMethod = request.getMethod();
        String params = "";
        if (("POST".equals(httpMethod) && !"application/x-www-form-urlencoded".equals(request.getHeader("Content-Type"))) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod)) {
            Object[] paramsArray = joinPoint.getArgs();
            // java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
            //  https://my.oschina.net/mengzhang6/blog/2395893
            Object[] arguments = new Object[paramsArray.length];
            for (int i = 0; i < paramsArray.length; i++) {
                if (paramsArray[i] instanceof ServletRequest || paramsArray[i] instanceof ServletResponse || paramsArray[i] instanceof MultipartFile) {
                    //ServletRequest不能序列化,从入参里排除,否则报异常:java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
                    //ServletResponse不能序列化 从入参里排除,否则报异常:java.lang.IllegalStateException: getOutputStream() has already been called for this response
                    continue;
                }
                arguments[i] = paramsArray[i];
            }
            //update-begin-author:taoyan date:20200724 for:日志数据太长的直接过滤掉
            PropertyFilter profilter = (o, name, value) -> {
                if (value != null && value.toString().length() > 500) {
                    return false;
                }
                return true;
            };
            if (isFilter) {
                params = JSONObject.toJSONString(arguments, profilter);
            } else {
                params = JSONObject.toJSONString(arguments);
            }
        } else {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            // 请求的方法参数值
            Object[] args = joinPoint.getArgs();
            // 请求的方法参数名称
            LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
            String[] paramNames = u.getParameterNames(method);
            if (args != null && paramNames != null) {
                for (int i = 0; i < args.length; i++) {
                    params += "  " + paramNames[i] + ": " + args[i];
                }
            }
        }
        return params;
    }

你可能感兴趣的:(spring,boot,java,后端)