Sl4j记录器在与ResponseEntityExceptionHandler一起用于捕获异常时不进行日志记录



我使用@ControllerAdvice创建了一个catch-all异常处理程序来捕获所有异常并相应地进行日志记录。但是,由于某些原因,sl4j记录器无法登录到控制台。同一个记录器在我的应用程序中的其他地方都可以工作,但它在catch-all异常处理程序中不起作用。

@ControllerAdvice
@Slf4j
public class CatchAllExceptionHandler extends ResponseEntityExceptionHandler {
private ResponseEntity<Object> buildResponseEntity(ApiError apiError) {
return new ResponseEntity<>(apiError, apiError.getStatus());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> catchAllExceptionHandler(Exception ex) {
ApiError apiError =
ApiError.builder()
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.message("An internal service issue")
.debugMessage(ex.getMessage())
.build();
log.debug("An issue has occurred, {}, {}", kv("message", ex.getMessage()),
kv("trace", ex.getStackTrace()));
return buildResponseEntity(apiError);
}
}

龙目的Sl4j已经被使用,但我不确定这是否与龙目有关。我可以看到超类(ResponseEntityExceptionHandler(有自己的logger,所以我不认为会发生任何奇怪的变量隐藏,但我不确定。

我非常确信我的日志配置文件和配置是正确的,因为它可以在除此catch-all异常处理程序之外的任何其他地方工作。它只是不在日志中打印任何内容。

更新:

我可以使用超类中的logger,它可以工作。然而,它使用的是apachecommons日志记录,这里缺少一些我需要的特定方法。

Spring引导默认日志级别为info,因此debug日志被抑制。我稍微修改了您的代码以重现该问题。

@ExceptionHandler(Exception.class)
public ResponseEntity<Object> catchAllExceptionHandler(Exception ex) {
log.info("******");
log.debug("An issue has occurred, {}", ex.getMessage());
log.info("An issue has occurred, {}", ex.getMessage());
log.info("******");
return ResponseEntity.status(500).build();
}

以上代码的输出:
仅查看打印的信息日志。

2020-09-03 22:25:45.065  INFO c.e.demo.main.CatchAllExceptionHandler   : ******
2020-09-03 22:25:45.065  INFO c.e.demo.main.CatchAllExceptionHandler   : An issue has occurred, test exception
2020-09-03 22:25:45.065  INFO c.e.demo.main.CatchAllExceptionHandler   : ******

解决方案1:
log.debug更改为log.infolog.warnlog.error。这套房适合您的情况。

解决方案2:
添加一个属性以启用application.propertiesCatchAllExceptionHandler的调试日志。

logging.level.com.example.demo.main.CatchAllExceptionHandler=debug

添加以上属性后的输出:

2020-09-03 22:36:05.389  INFO c.e.demo.main.CatchAllExceptionHandler   : ******
2020-09-03 22:36:05.389 DEBUG c.e.demo.main.CatchAllExceptionHandler   : An issue has occurred, test exception
2020-09-03 22:36:05.389  INFO c.e.demo.main.CatchAllExceptionHandler   : An issue has occurred, test exception
2020-09-03 22:36:05.389  INFO c.e.demo.main.CatchAllExceptionHandler   : ******

最新更新