简体   繁体   中英

How to log the incoming json request in spring restful webservice with restcontroller?

I want to log all the incoming requests which will be in json format.I am using spring @RestController and @RequestBody annotations to bind the incoming json content to java objects.But i want to log these requests to logger files.I have searched around for objectmapper and jacksonbinding.

@RestController
public class restClassName{

@RequestMapping(value={"/uri"})
public ObjectResponse functionRestName(@RequestBody ObjectRequest or){
  String jsonInString = mapper.writeValueAsString(staff);//Redundant stuff as the request json is already read by MappingJackson2HttpMessageConverter
  logger.info("request::"+jsonInString)
  return instance;
}
}

But this seems to be a rendundant way of doing.Since MappingJackson2HttpMessageConverter already reads the httprequest to convert json request to java object.I just need to log the json before MappingJackson2HttpMessageConverter converts the request json to java object.

The simplest way to achieve it is to use CommonsRequestLoggingFilter as described in below pseudo code.

@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
    CommonsRequestLoggingFilter crlf = new CommonsRequestLoggingFilter();
    crlf.setIncludeClientInfo(true);
    crlf.setIncludeQueryString(true);
    crlf.setIncludePayload(true);
    return crlf;
}

Then in application.properties file add the follwing line.

logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG

This will log all the requests, please follow the link to CommonsRequestLoggingFilter api doc for more customization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM