Spring Cloud Sleuth is one of the spring cloud component which used to corelate log between different service. It is useful when tracking problem and it can draw the full picture from start to end.
However, it only apply for controller to diagnosis. spin and trace id will miss when exception thrown. This article will status how to resolve this problem.
In Springboot MVC project, it simply add new ControllerAdvice to capture exception and it can be resolve.
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; @ControllerAdvice public class ControllerExceptionHandler { private static final Logger logger= LogManager.getLogger(ControllerExceptionHandler.class); @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(Exception.class) @ResponseBody public void handleInternalError(Exception exception) { logger.error(exception.getMessage(),exception); } }
Screenshot of test result, trace Id and spin Id shown in log.
Leave a Reply