Home > OS >  How to log json response in Spring Boot?
How to log json response in Spring Boot?

Time:05-27

If I define a response entity class and return it by my rest controller, controller will change this class to json string. I want to log this json string, how to do it? Thanks.

For example:

Response entity class:

@Data
@AllArgsConstructor
public class ResponseEntity {
    String code;
    String message;
}

Rest Controller:

@RestController
@RequestMapping("/")
public class StudentController {
    @RequestMapping("test")
    public ResponseEntity test(){
        return new ResponseEntity(200,"success");
    }
}

I want to record this json response in log

{"code":200,"message":"success"}

CodePudding user response:

The simplest and handy way is convert it to JSON string manually and then log it. You can convert it to JSON by ObjectMapper.

@Log4j2
@RequestMapping("/")
public class StudentController {

    @Autowired
    private ObjectMapper objectMapper;

    @RequestMapping("test")
    public ResponseEntity test() throws Exception {
        ResponseEntity entity = new ResponseEntity(200, "success");
        log.debug("{}", objectMapper.writeValueAsString(entity));
        return entity;
    }
}

Or you can use Logstash json_event pattern for log4j if you need advanced feature.

CodePudding user response:

In order to accomplish you desired behaviour the spring framework offers an utility class which does exactly the requested job for your.

Just declare this:

@Configuration
public class RequestLoggingFilterConfig {

@Bean
public CommonsRequestLoggingFilter logFilter() {
    CommonsRequestLoggingFilter filter
      = new CommonsRequestLoggingFilter();
    filter.setIncludeQueryString(true);
    filter.setIncludePayload(true);
    filter.setMaxPayloadLength(10000);
    filter.setIncludeHeaders(false);
    filter.setAfterMessagePrefix("REQUEST DATA : ");
    return filter;
}
}

And add to your logging file this appender:

<logger name="org.springframework.web.filter.CommonsRequestLoggingFilter">
<level value="DEBUG" />
</logger>

Same result can be done with this application.properties property

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

this should be enough, but, in case you want a fine grained control on the logging operation you can create your own filter by extending AbstractRequestLoggingFilter .

  • Related