如何使用Spring MVC正确记录http请求 [英] How to log properly http requests with Spring MVC

查看:259
本文介绍了如何使用Spring MVC正确记录http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我一直在试图找出在我的应用程序中记录http请求的通用方法,到目前为止没有运气,这是我现在如何处理日志记录,即:

Hello I've been trying to figure out generic way to log http requests in my application, so far no luck, here is how I handle the logging right now i.e:

@RequestMapping(value="register", method = RequestMethod.POST)
    @ResponseBody
    public String register(@RequestParam(value="param1",required=false) String param1, @RequestParam("param2") String param2, @RequestParam("param3") String param3, HttpServletRequest request){
        long start = System.currentTimeMillis();
        logger.info("!--REQUEST START--!");

        logger.info("Request URL: " + request.getRequestURL().toString());

        List<String> requestParameterNames = Collections.list((Enumeration<String>)request.getParameterNames());
        logger.info("Parameter number: " + requestParameterNames.size()); 

 for (String parameterName : requestParameterNames){
           logger.info("Parameter name: " + parameterName + " - Parameter value: " + request.getParameter(parameterName));
        }
                  //Some processing logic, call to the various services/methods with different parameters, response is always String(Json)
        String response = service.callSomeServiceMethods(param1,param2,param3);

logger.info("Response is: " + response);

        long end = System.currentTimeMillis();
        logger.info("Requested completed in: " + (end-start) + "ms");
        logger.info("!--REQUEST END--!");   

        return response;
    }

所以我现在对不同的控制器/方法所做的就是从头开始复制一切方法内部直到处理逻辑不同于方法,然后复制下面的所有内容,如上面的模板所示。

So what I do right now for different controllers/methods is copy everything from beginning of the inside of the method until the processing logic which differs from method to method and then copy everything from below of that as showed in above template.

这有点乱,并且有很多代码重复(我不喜欢)。但是我需要记录所有内容。

It is kind of messy, and there is a lot of code repetition(which I don't like). But I need to log everything.

有没有人对这种日志记录有更多的经验,有人可以对此有所了解吗?

Does anyone have more experience with this kinds of logging, can anyone shed some light on this?

推荐答案

使用拦截器


  • extend HandlerInterceptorAdapter 并覆盖 preHandle

  • 使用< mvc:interceptors>定义它 in dispatcher-servlet.xml

  • extend HandlerInterceptorAdapter and override preHandle
  • define it with <mvc:interceptors> in dispatcher-servlet.xml

It将为每个请求运行。

It will run for every request.

这篇关于如何使用Spring MVC正确记录http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆