当前位置:   article > 正文

springboot整合日志功能_如何给spring boot项目添加日志功能

如何给spring boot项目添加日志功能

1、引入依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-aop</artifactId>
  4. </dependency>

2、application.yml配置

  1. # 日志配置
  2. logging:
  3. level:
  4. com.xiaomin.page: debug

3、定义切面类

  1. package com.xiaomin.page.aspect;
  2. import org.aspectj.lang.JoinPoint;
  3. import org.aspectj.lang.annotation.AfterReturning;
  4. import org.aspectj.lang.annotation.Aspect;
  5. import org.aspectj.lang.annotation.Before;
  6. import org.aspectj.lang.annotation.Pointcut;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.stereotype.Component;
  10. import org.springframework.web.context.request.RequestContextHolder;
  11. import org.springframework.web.context.request.ServletRequestAttributes;
  12. import javax.servlet.http.HttpServletRequest;
  13. import java.util.Arrays;
  14. /**
  15. * @author 晓敏
  16. * @create 2020-03-26 15:11
  17. */
  18. @Aspect
  19. @Component
  20. public class WebLog {
  21. private Logger logger = LoggerFactory.getLogger(WebLog.class);
  22. /**
  23. * 配置切入点
  24. */
  25. @Pointcut("execution(* com.xiaomin.page.controller.*.*(..))")
  26. public void webLog(){}
  27. @Before("webLog()")
  28. public void doBefore(JoinPoint joinPoint) throws Throwable {
  29. // 接收到请求,记录请求内容
  30. ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  31. HttpServletRequest request = attributes.getRequest();
  32. // 记录下请求内容
  33. logger.info("URL : " + request.getRequestURL().toString());
  34. logger.info("HTTP_METHOD : " + request.getMethod());
  35. logger.info("IP : " + request.getRemoteAddr());
  36. logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
  37. logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
  38. }
  39. @AfterReturning(returning = "ret",pointcut = "webLog()")
  40. public void doAfterReturning(Object ret) throws Throwable {
  41. // 处理完请求,返回内容
  42. logger.info("RESPONSE : " + ret);
  43. }
  44. }

3、测试

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/1011738
推荐阅读
相关标签
  

闽ICP备14008679号