[Spring] Resolve issue on no trace Id and spin Id logged

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.

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.