简体   繁体   中英

Logging request body in json?

@PostMapping()
public ResponseEntity<?> getCall(@Valid @RequestBody Request request) {
    String requestJson = null;
    try {
        requestJson = ObjectMapperUtil.writeValueAsString(request);
        log.info(requestJson) // will this introduce latency in my api.
        return ResponseEntity.ok(service.getData(request));
    } catch (Exception e) {
        log.error(requestJson);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Request.builder().errors(INTERNAL_SERVER_ERROR)).build());
    }

}

Just want to know that if we print the request body in json format after converting using ObjectMapper, what will be the impact on the latency on the api. Should we go ahead with @toString logging only. What's the good trade-off here.

If you're worried about latency, add an if statement around that code (most logging frameworks have such check methods):

String requestJson = null;
try {
    if (log.isInfoEnabled()) {
        requestJson = ObjectMapperUtil.writeValueAsString(request);
        log.info(requestJson);
    }
    return ResponseEntity.ok(service.getData(request));
} catch (Exception e) {
    if (requestJson != null) {
        log.error(requestJson, e);
    } else {
        log.error("Failed to convert '{}' to JSON", request, e);
    }
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Request.builder().errors(INTERNAL_SERVER_ERROR)).build());
}

Note that if the conversion of the object to JSON fails, requestJson will remain null , and there's no point in logging it. I also didn't add a check for log.isErrorEnabled() because a) that's almost always the case, and b) there's no logic involved in the error logging; any filtering will be done by the logger itself. Also note that I included the exception in the logging as well - you really want to know why the failure occurred.

There will still be latency, but only if needed. You can also consider moving the conversion into the catch (which needs its own try-catch). That way, the request JSON will only be logged if there's an error.

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