Java Spring 日志

切面介绍

面向切面编程是一种编程范式,它作为OOP面向对象编程的一种补充,用于处理系统中分布于各个模块的横切关注点,比如事务管理、权限控制、缓存控制、日志打印等等。AOP把软件的功能模块分为两个部分:核心关注点和横切关注点。业务处理的主要功能为核心关注点,而非核心、需要拓展的功能为横切关注点。AOP的作用在于分离系统中的各种关注点,将核心关注点和横切关注点进行分离,使用切面有以下好处:

  • 集中处理某一关注点/横切逻辑
  • 可以很方便的添加/删除关注点
  • 侵入性少,增强代码可读性及可维护性

因此当想打印请求日志时很容易想到切面,对控制层代码0侵入

切面的使用【基于注解】

  • @Aspect => 声明该类为一个注解类

    切点注解:

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

    通知注解:

  • @Before => 在切点之前执行代码

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

    动手写一个请求日志切面

    使用@Pointcut定义切点

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

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

    使用@Before再切点前执行

    1. @Before("requestServer()")
    2. public void doBefore(JoinPoint joinPoint) {
    3. ServletRequestAttributes attributes = (ServletRequestAttributes)
    4. RequestContextHolder.getRequestAttributes();
    5. HttpServletRequest request = attributes.getRequest();
    6. LOGGER.info("===============================Start========================");
    7. LOGGER.info("IP : {}", request.getRemoteAddr());
    8. LOGGER.info("URL : {}", request.getRequestURL().toString());
    9. LOGGER.info("HTTP Method : {}", request.getMethod());
    10. LOGGER.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
    11. }

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

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

    1. @Around("requestServer()")
    2. public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    3. long start = System.currentTimeMillis();
    4. Object result = proceedingJoinPoint.proceed();
    5. LOGGER.info("Request Params : {}", getRequestParams(proceedingJoinPoint));
    6. LOGGER.info("Result : {}", result);
    7. LOGGER.info("Time Cost : {} ms", System.currentTimeMillis() - start);
    8. return result;
    9. }

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

    getRquestParams方法

    1. private Map<String, Object> getRequestParams(ProceedingJoinPoint proceedingJoinPoint) {
    2. Map<String, Object> requestParams = new HashMap<>();
    3. //参数名
    4. String[] paramNames = ((MethodSignature)proceedingJoinPoint.getSignature()).getParameterNames();
    5. //参数值
    6. Object[] paramValues = proceedingJoinPoint.getArgs();
    7. for (int i = 0; i < paramNames.length; i++) {
    8. Object value = paramValues[i];
    9. //如果是文件对象
    10. if (value instanceof MultipartFile) {
    11. MultipartFile file = (MultipartFile) value;
    12. value = file.getOriginalFilename(); //获取文件名
    13. }
    14. requestParams.put(paramNames[i], value);
    15. }
    16. return requestParams;
    17. }

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

    @After方法调用后执行

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

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

    完整切面代码

    ```java @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) {

    1. ServletRequestAttributes attributes = (ServletRequestAttributes)
    2. RequestContextHolder.getRequestAttributes();
    3. HttpServletRequest request = attributes.getRequest();
    4. LOGGER.info("===============================Start========================");
    5. LOGGER.info("IP : {}", request.getRemoteAddr());
    6. LOGGER.info("URL : {}", request.getRequestURL().toString());
    7. LOGGER.info("HTTP Method : {}", request.getMethod());
    8. LOGGER.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(),
    9. joinPoint.getSignature().getName());

    }

  1. @Around("requestServer()")
  2. public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
  3. long start = System.currentTimeMillis();
  4. Object result = proceedingJoinPoint.proceed();
  5. LOGGER.info("Request Params : {}", getRequestParams(proceedingJoinPoint));
  6. LOGGER.info("Result : {}", result);
  7. LOGGER.info("Time Cost : {} ms", System.currentTimeMillis() - start);
  8. return result;
  9. }
  10. @After("requestServer()")
  11. public void doAfter(JoinPoint joinPoint) {
  12. LOGGER.info("===============================End========================");
  13. }
  14. /**
  15. * 获取入参
  16. * @param proceedingJoinPoint
  17. *
  18. * @return
  19. * */
  20. private Map<String, Object> getRequestParams(ProceedingJoinPoint proceedingJoinPoint) {
  21. Map<String, Object> requestParams = new HashMap<>();
  22. //参数名
  23. String[] paramNames =
  24. ((MethodSignature)proceedingJoinPoint.getSignature()).getParameterNames();
  25. //参数值
  26. Object[] paramValues = proceedingJoinPoint.getArgs();
  27. for (int i = 0; i < paramNames.length; i++) {
  28. Object value = paramValues[i];
  29. //如果是文件对象
  30. if (value instanceof MultipartFile) {
  31. MultipartFile file = (MultipartFile) value;
  32. value = file.getOriginalFilename(); //获取文件名
  33. }
  34. requestParams.put(paramNames[i], value);
  35. }
  36. return requestParams;
  37. }

}

  1. <a name="xQbcx"></a>
  2. ## 高并发下请求日志切面
  3. 每个信息都打印一行,在高并发请求下确实会出现请求之间打印日志串行的问题,因为测试阶段请求数量较少没有出现串行的情况,果然生产环境才是第一发展力,能够遇到更多bug,写更健壮的代码 解决日志串行的问题只要将多行打印信息合并为一行就可以了,因此构造一个对象
  4. <a name="IQ1oz"></a>
  5. ### RequestInfo.java
  6. ```java
  7. @Data
  8. public class RequestInfo {
  9. private String ip;
  10. private String url;
  11. private String httpMethod;
  12. private String classMethod;
  13. private Object requestParams;
  14. private Object result;
  15. private Long timeCost;
  16. }

环绕通知方法体

  1. @Around("requestServer()")
  2. public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
  3. long start = System.currentTimeMillis();
  4. ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  5. HttpServletRequest request = attributes.getRequest();
  6. Object result = proceedingJoinPoint.proceed();
  7. RequestInfo requestInfo = new RequestInfo();
  8. requestInfo.setIp(request.getRemoteAddr());
  9. requestInfo.setUrl(request.getRequestURL().toString());
  10. requestInfo.setHttpMethod(request.getMethod());
  11. requestInfo.setClassMethod(String.format("%s.%s", proceedingJoinPoint.getSignature().getDeclaringTypeName(),
  12. proceedingJoinPoint.getSignature().getName()));
  13. requestInfo.setRequestParams(getRequestParamsByProceedingJoinPoint(proceedingJoinPoint));
  14. requestInfo.setResult(result);
  15. requestInfo.setTimeCost(System.currentTimeMillis() - start);
  16. LOGGER.info("Request Info : {}", JSON.toJSONString(requestInfo));
  17. return result;
  18. }

将url、http request这些信息组装成RequestInfo对象,再序列化打印对象
打印序列化对象结果而不是直接打印对象是因为序列化有更直观、更清晰,同时可以借助在线解析工具对结果进行解析
2021-07-21-21-39-48-826786.png
在解决高并发下请求串行问题的同时添加了对异常请求信息的打印,通过使用 @AfterThrowing注解对抛出异常的方法进行处理

RequestErrorInfo.java

  1. @Data
  2. public class RequestErrorInfo {
  3. private String ip;
  4. private String url;
  5. private String httpMethod;
  6. private String classMethod;
  7. private Object requestParams;
  8. private RuntimeException exception;
  9. }

异常通知环绕体

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

对于异常,耗时是没有意义的,因此不统计耗时,而是添加了异常的打印
完整日志请求切面代码:

  1. @Component
  2. @Aspect
  3. public class RequestLogAspect {
  4. private final static Logger LOGGER = LoggerFactory.getLogger(RequestLogAspect.class);
  5. @Pointcut("execution(* your_package.controller..*(..))")
  6. public void requestServer() {
  7. }
  8. @Around("requestServer()")
  9. public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
  10. long start = System.currentTimeMillis();
  11. ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  12. HttpServletRequest request = attributes.getRequest();
  13. Object result = proceedingJoinPoint.proceed();
  14. RequestInfo requestInfo = new RequestInfo();
  15. requestInfo.setIp(request.getRemoteAddr());
  16. requestInfo.setUrl(request.getRequestURL().toString());
  17. requestInfo.setHttpMethod(request.getMethod());
  18. requestInfo.setClassMethod(String.format("%s.%s", proceedingJoinPoint.getSignature().getDeclaringTypeName(),
  19. proceedingJoinPoint.getSignature().getName()));
  20. requestInfo.setRequestParams(getRequestParamsByProceedingJoinPoint(proceedingJoinPoint));
  21. requestInfo.setResult(result);
  22. requestInfo.setTimeCost(System.currentTimeMillis() - start);
  23. LOGGER.info("Request Info : {}", JSON.toJSONString(requestInfo));
  24. return result;
  25. }
  26. @AfterThrowing(pointcut = "requestServer()", throwing = "e")
  27. public void doAfterThrow(JoinPoint joinPoint, RuntimeException e) {
  28. ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  29. HttpServletRequest request = attributes.getRequest();
  30. RequestErrorInfo requestErrorInfo = new RequestErrorInfo();
  31. requestErrorInfo.setIp(request.getRemoteAddr());
  32. requestErrorInfo.setUrl(request.getRequestURL().toString());
  33. requestErrorInfo.setHttpMethod(request.getMethod());
  34. requestErrorInfo.setClassMethod(String.format("%s.%s", joinPoint.getSignature().getDeclaringTypeName(),
  35. joinPoint.getSignature().getName()));
  36. requestErrorInfo.setRequestParams(getRequestParamsByJoinPoint(joinPoint));
  37. requestErrorInfo.setException(e);
  38. LOGGER.info("Error Request Info : {}", JSON.toJSONString(requestErrorInfo));
  39. }
  40. /**
  41. * 获取入参
  42. * @param proceedingJoinPoint
  43. *
  44. * @return
  45. * */
  46. private Map<String, Object> getRequestParamsByProceedingJoinPoint(ProceedingJoinPoint proceedingJoinPoint) {
  47. //参数名
  48. String[] paramNames = ((MethodSignature)proceedingJoinPoint.getSignature()).getParameterNames();
  49. //参数值
  50. Object[] paramValues = proceedingJoinPoint.getArgs();
  51. return buildRequestParam(paramNames, paramValues);
  52. }
  53. private Map<String, Object> getRequestParamsByJoinPoint(JoinPoint joinPoint) {
  54. //参数名
  55. String[] paramNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
  56. //参数值
  57. Object[] paramValues = joinPoint.getArgs();
  58. return buildRequestParam(paramNames, paramValues);
  59. }
  60. private Map<String, Object> buildRequestParam(String[] paramNames, Object[] paramValues) {
  61. Map<String, Object> requestParams = new HashMap<>();
  62. for (int i = 0; i < paramNames.length; i++) {
  63. Object value = paramValues[i];
  64. //如果是文件对象
  65. if (value instanceof MultipartFile) {
  66. MultipartFile file = (MultipartFile) value;
  67. value = file.getOriginalFilename(); //获取文件名
  68. }
  69. requestParams.put(paramNames[i], value);
  70. }
  71. return requestParams;
  72. }
  73. @Data
  74. public class RequestInfo {
  75. private String ip;
  76. private String url;
  77. private String httpMethod;
  78. private String classMethod;
  79. private Object requestParams;
  80. private Object result;
  81. private Long timeCost;
  82. }
  83. @Data
  84. public class RequestErrorInfo {
  85. private String ip;
  86. private String url;
  87. private String httpMethod;
  88. private String classMethod;
  89. private Object requestParams;
  90. private RuntimeException exception;
  91. }
  92. }