转:Spring Boot中使用AOP统一处理Web请求日志

时间:2023-11-21 22:36:08

在spring boot中,简单几步,使用spring AOP实现一个拦截器:

1、引入依赖:

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

2、创建拦截器类(在该类中,定义了拦截规则:拦截com.xjj.web.controller包下面的所有类中,有@RequestMapping注解的方法。):

    1. /**
    2. * 拦截器:记录用户操作日志,检查用户是否登录……
    3. * @author XuJijun
    4. */
    5. @Aspect
    6. @Component
    7. public class ControllerInterceptor {
    8. private static final Logger logger = LoggerFactory.getLogger(ControllerInterceptor.class);
    9. @Value(“${spring.profiles}”)
    10. private String env;
    11. /**
    12. * 定义拦截规则:拦截com.xjj.web.controller包下面的所有类中,有@RequestMapping注解的方法。
    13. */
    14. @Pointcut(“execution(* com.xjj.web.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)”)
    15. public void controllerMethodPointcut(){}
    16. /**
    17. * 拦截器具体实现
    18. * @param pjp
    19. * @return JsonResult(被拦截方法的执行结果,或需要登录的错误提示。)
    20. */
    21. @Around(“controllerMethodPointcut()”) //指定拦截器规则;也可以直接把“execution(* com.xjj………)”写进这里
    22. public Object Interceptor(ProceedingJoinPoint pjp){
    23. long beginTime = System.currentTimeMillis();
    24. MethodSignature signature = (MethodSignature) pjp.getSignature();
    25. Method method = signature.getMethod(); //获取被拦截的方法
    26. String methodName = method.getName(); //获取被拦截的方法名
    27. Set<Object> allParams = new LinkedHashSet<>(); //保存所有请求参数,用于输出到日志中
    28. logger.info(”请求开始,方法:{}”, methodName);
    29. Object result = null;
    30. Object[] args = pjp.getArgs();
    31. for(Object arg : args){
    32. //logger.debug(“arg: {}”, arg);
    33. if (arg instanceof Map<?, ?>) {
    34. //提取方法中的MAP参数,用于记录进日志中
    35. @SuppressWarnings(“unchecked”)
    36. Map<String, Object> map = (Map<String, Object>) arg;
    37. allParams.add(map);
    38. }else if(arg instanceof HttpServletRequest){
    39. HttpServletRequest request = (HttpServletRequest) arg;
    40. if(isLoginRequired(method)){
    41. if(!isLogin(request)){
    42. result = new JsonResult(ResultCode.NOT_LOGIN, “该操作需要登录!去登录吗?\n\n(不知道登录账号?请联系老许。)”, null);
    43. }
    44. }
    45. //获取query string 或 posted form data参数
    46. Map<String, String[]> paramMap = request.getParameterMap();
    47. if(paramMap!=null && paramMap.size()>0){
    48. allParams.add(paramMap);
    49. }
    50. }else if(arg instanceof HttpServletResponse){
    51. //do nothing…
    52. }else{
    53. //allParams.add(arg);
    54. }
    55. }
    56. try {
    57. if(result == null){
    58. // 一切正常的情况下,继续执行被拦截的方法
    59. result = pjp.proceed();
    60. }
    61. } catch (Throwable e) {
    62. logger.info(”exception: ”, e);
    63. result = new JsonResult(ResultCode.EXCEPTION, “发生异常:”+e.getMessage());
    64. }
    65. if(result instanceof JsonResult){
    66. long costMs = System.currentTimeMillis() - beginTime;
    67. logger.info(”{}请求结束,耗时:{}ms”, methodName, costMs);
    68. }
    69. return result;
    70. }
    71. /**
    72. * 判断一个方法是否需要登录
    73. * @param method
    74. * @return
    75. */
    76. private boolean isLoginRequired(Method method){
    77. if(!env.equals(“prod”)){ //只有生产环境才需要登录
    78. return false;
    79. }
    80. boolean result = true;
    81. if(method.isAnnotationPresent(Permission.class)){
    82. result = method.getAnnotation(Permission.class).loginReqired();
    83. }
    84. return result;
    85. }
    86. //判断是否已经登录
    87. private boolean isLogin(HttpServletRequest request) {
    88. return true;
    89. /*String token = XWebUtils.getCookieByName(request, WebConstants.CookieName.AdminToken);
    90. if(“1”.equals(redisOperator.get(RedisConstants.Prefix.ADMIN_TOKEN+token))){
    91. return true;
    92. }else {
    93. return false;
    94. }*/
    95. }
    96. }