日志请求体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());
}
}

只是想知道,如果我们在使用ObjectMapper转换后以json格式打印请求正文,对api的延迟会有什么影响?我们应该只使用@toString日志记录吗?什么是好的权衡呢?

如果您担心延迟,请在该代码周围添加If语句(大多数日志框架都有这样的检查方法):

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());
}

请注意,如果对象到JSON的转换失败,requestJson将保持null,并且没有必要记录它。我也没有为log.isErrorEnabled()添加检查,因为a)几乎总是如此,b)错误记录中没有涉及逻辑;任何过滤都将由记录器本身完成。还请注意,我在日志记录中也包含了异常—您确实想知道为什么发生故障。

仍然会有延迟,但只有在需要时才会有。还可以考虑将转换移到catch中(它需要自己的try-catch)。这样,只有在出现错误时,请求JSON才会被记录。

最新更新