本篇内容主要讲解“springboot-WebLogAspect用于记录请求和响应日志的实现方法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“springboot-WebLogAspect用于记录请求和响应日志的实现方法”吧!
用途
用于记录spring boot的请求和响应日志; aop实现;
依赖
lombok -如果没有,可以自已创建log对象
Slf4j -
jackson
apache common
实现
package xxx.xxx.xxx; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; /** * 用于记录web请求/响应日志 */ @Component @Aspect @Slf4j public class WebLogAspect { /** * 切面, xxx.xxx.xxx.web.ctl是Controller包名 */ @Pointcut("execution(* xxx.xxx.xxx.web.ctl..*.*(..))") private void parameterPointCut() { } /** * 方法执行前,记录请求 * @param joinPoint */ @Before("parameterPointCut()") public void requestLog(JoinPoint joinPoint){ RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//这个RequestContextHolder是Springmvc提供来获得请求的东西 HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest(); String queryStr = request.getQueryString(); if(StringUtils.isNotEmpty(queryStr)){ log.info("请求地址: [{}] {}", request.getMethod(), request.getRequestURI()); }else{ log.info("请求地址: [{}] {}?{} ", request.getMethod(), request.getRequestURI(), queryStr); } printRequestArgs(joinPoint); } private void printRequestArgs(JoinPoint joinPoint){ log.info("请求方法: {}", joinPoint.toString()); Object[] reqArgs = joinPoint.getArgs(); if(null == reqArgs){ return; } int c = 0; ObjectMapper mapper = new ObjectMapper(); for(Object arg: reqArgs){ try{ log.info("请求入参[{}]: {}", c, mapper.writeValueAsString(arg)); }catch (Exception ex){ log.error("请求入参转换异常", ex); } c++; } } /** * 方法执行后,记录响应 * @param joinPoint * @param ret 方法执行结果注入对象 * @return */ @AfterReturning(returning = "ret",pointcut = "parameterPointCut()") public Object responeLog(JoinPoint joinPoint, Object ret){ try { ObjectMapper mapper = new ObjectMapper(); log.info("响应出参: {}", mapper.writeValueAsString(ret)); } catch (Throwable ex) { log.error("响应异常", ex); } return ret; } }
到此,相信大家对“springboot-WebLogAspect用于记录请求和响应日志的实现方法”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。