问题描述
我已经使用@ControllerAdvice
创建了一个包罗万象的异常处理程序,以捕获所有异常并进行相应记录。但是,由于某种原因,sl4j记录器无法登录到控制台。相同的记录器在我的应用程序中的每个其他位置都起作用,但在全部捕获的异常处理程序中却不起作用。
@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);
}
}
已经使用了Lombok的 Sl4j
,但是我不确定这是否与Lombok有关。我可以看到超类(ResponseEntityExceptionHandler
)有自己的logger
,所以我认为没有任何奇怪的变量隐藏正在发生,但我不确定。
我非常确定我的日志记录配置文件和配置正确无误,因为它可以在除此包罗万象的异常处理程序之外的其他任何地方工作。它只是根本不打印日志中的任何内容。
更新:
我可以使用超类中的logger,它可以工作。但是,它使用的是apache commons-logging,但这里缺少我需要的一些特定方法。
解决方法
Spring Boot的默认日志级别为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.info
或log.warn
或log.error
。这种情况适合您的情况。
解决方案2:
在CatchAllExceptionHandler
中添加属性以为application.properties
启用调试日志。
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 : ******