一些项目,特别是接收一些老项目,里面都没有很规范的打印日志,一个一个添加不现实,编写一个切面工具类,直接打印接口的请求出入参数 @Aspect @Component public class LogAopAspect { private final Logger log = ESAPI.getLogger(this.getClass()); private static final String REGEX = "#.+?#"; private final String REQUEST_MESSAGE_BODY = "发送请求:#方法名#:#请求路径#:请求入参:#请求体#"; private final String RESPONSE_MESSAGE_BODY = "请求响应:#方法名#:#请求路径#:响应出参:#响应体#"; @Pointcut("execution(* cn.com.aia.acn.bizportal.controller..*.*(..)) ") public void logPointCut() { } @Around("logPointCut()") public Object logPointAround(ProceedingJoinPoint pjp) throws Throwable { Signature signature = pjp.getSignature(); String clzName = signature.getDeclaringTypeName().substring(signature.getDeclaringTypeName().lastIndexOf(".")+1,signature.getDeclaringTypeName().length()); String methodDesc = clzName + "." + signature.getName(); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); return printLog(methodDesc, request, pjp); } private Object printLog(String methodDesc, HttpServletRequest request, ProceedingJoinPoint pjp) throws Throwable { String method = request.getMethod(); if (method.equals("GET")) { Map<String, String[]> parameterMap = request.getParameterMap(); String content1 = replaceString(REQUEST_MESSAGE_BODY,methodDesc, request.getRequestURI(), JSON.toJSONString(parameterMap)); log.info(Logger.EVENT_SUCCESS,content1); } else if (method.equals("POST")) { //获取请求body byte[] bodyBytes = StreamUtils.copyToByteArray(request.getInputStream()); String body = new String(bodyBytes, request.getCharacterEncoding()); String content2 = replaceString(REQUEST_MESSAGE_BODY,methodDesc, request.getRequestURI(), body); log.info(Logger.EVENT_SUCCESS,content2); } Object obj = pjp.proceed(); String content3 = replaceString(RESPONSE_MESSAGE_BODY,methodDesc, request.getRequestURI(), JSON.toJSONString(obj)); log.info(Logger.EVENT_SUCCESS,content3); return obj; } public static String replaceString(String text, String ...values) { for (String value : values) { if(StringUtils.isBlank(value)) { value = ""; } text = text.replaceFirst(REGEX,value); } return text; } }
java 记录日志切面工具类
最新推荐文章于 2024-10-06 02:11:52 发布