如何在Spring MVC中记录传入请求

时间:2019-05-22 05:37:33

标签: java spring spring-mvc

我有这样的JSON请求正文

{  
   "3DSecure":{  
      "paRes":"xxxxxxxxxxxxxxxxxxxxxxx"
   }
}

我开发了端点来记录该请求。

@RequestMapping(value = "/logging/requests", method = RequestMethod.POST)
@ResponseBody
public String loggingIncomingRequest(@RequestBody AxiPayCargilsRequest request,
                                         HttpServletRequest servletRequest,
                                         ServiceContext serviceContext){

    log.info("!--REQUEST START--!"+request);

    log.info("");
    return null;
}

如何记录此请求,任何人都可以从对象创建的层面帮助我 谢谢。

2 个答案:

答案 0 :(得分:0)

首先,在pom.xml中添加以下依赖项

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.11.2</version>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.11.2</version>
  </dependency>

然后在需要记录日志的所有类中初始化记录器,

private final static Logger logger  = LogManager.getFormatterLogger(YourClassName.class);

现在,您可以使用类似的记录器

logger.info("Your Logging info");

答案 1 :(得分:0)

使用过滤器,您可以处理进入应用程序的所有请求。

    @Component
    public class SimpleRequestFilter implements Filter {

        private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);

        public SimpleCORSFilter() {
            log.info("SimpleCORSFilter init");
        }

        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
                throws IOException, ServletException {

            // HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
            log.info("Request URI: " + request.getRequestURI());
            // Similarily, you can log others properties as required.

            chain.doFilter(req, res);
        }

        @Override
        public void init(FilterConfig filterConfig) {
        }

        @Override
        public void destroy() {
        }

    }

如果您要登录,只需说一个API请求,就可以遵循@Chirag Shah的回答。