package com.tanpu.fund.config.log; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.tanpu.common.exception.TanPuException; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import java.net.URLDecoder; /** * @description: * @author: wanglei * @created: 2020/04/16 22:40 */ @Aspect @Configuration @Slf4j public class LoggerAspect { // 定义切点Pointcut @Pointcut("execution(* com.tanpu.fund.controller..*.*(..))") public void executeService() { } @Around("executeService()") public Object doAround(ProceedingJoinPoint pjp) throws Throwable { long start = System.currentTimeMillis(); Object result = null; try { RequestAttributes ra = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes) ra; HttpServletRequest request = sra.getRequest(); String url = request.getRequestURI(); String method = request.getMethod(); String params = ""; if ("POST".equals(method) || "PUT".equals(method)) { Object[] args = pjp.getArgs(); Object[] arguments = new Object[args.length]; for (int i = 0; i < args.length; i++) { if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[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] = args[i]; } //获取请求参数集合并进行遍历拼接 if (arguments.length > 0) { params = JSONObject.toJSONString(arguments); } } else if ("GET".equals(method)) { if (StringUtils.isNotBlank(request.getQueryString())) { params = URLDecoder.decode(request.getQueryString(), "UTF-8"); } } log.info("请求开始===地址{},类型:{},参数:{}", url, method, params); // result的值就是被拦截方法的返回值 result = pjp.proceed(); log.info("返回值:{}", JSON.toJSON(result)); } catch (TanPuException e) { log.info("处理失败 :{}", e.getMessage()); throw e; } catch (Throwable e) { throw e; } finally { log.info("耗时:{}", System.currentTimeMillis() - start); } return result; } }