In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
In this issue, the editor will bring you about how to achieve simple distributed log tracking for micro services. The article is rich in content and analyzed and described from a professional point of view. I hope you can get something after reading this article.
Recently, I want to add a simple distributed request tracking function to the project, from the front end to the gateway to initiate the request, and then call the Spring Cloud micro service from the gateway. In these processes, I hope to see a distributed ID link from the log, and the entire link can be tracked through the requested ID to facilitate problem troubleshooting.
The off-the-shelf solution is to use components such as SkyWalking, Spring Cloud Sleuth, Zipkin, and so on, but the main purpose is to record an ID that can run through various services all the time to facilitate log query, so you don't want to introduce too many complex components, so you finally decide to output the tracked ID in the log through MDC, and then request ID to be passed on in the micro service in Feign and RestTemplate.
It mainly includes several steps:
Generate the request ID from the front end and add the request header to the gateway
The gateway is intercepted by WebFilter and added to MDC, and output in log.
Transfer the request ID to the microservice in the Header brought to HTTP in Feign and RequestTemplate
Each microservice is also intercepted through WebFilter and added to MDC, which is output in log.
MDC
MDC (Mapped Diagnostic Context, mapping debug context) is a function provided by Log4j and Logback to facilitate logging under multithreaded conditions. MDC can be thought of as a hash table bound to the current thread to which you can add key-value pairs.
Key operations of MDC:
Set the value to MDC: MDC.put (key, value)
Take a value from MDC: MDC.get (key)
Print the contents of MDC to the log:% X {key}
New TraceId tool class
First, a new TraceIdUtils utility class is added, which is used to define the constant value of TRACE_ID and the method of setting and generating TRACE_ID, which is used in the subsequent code.
Import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.MDC; public class TraceIdUtils {public static final String TRACE_ID = "traceId"; private static final int MAX_ID_LENGTH = 10; / * generate traceId * / private static String genTraceId () {return RandomStringUtils.randomAlphanumeric (MAX_ID_LENGTH) } / * set traceId * / public static void setTraceId (String traceId) {/ / if the parameter is empty, generate a new ID traceId = StringUtils.isBlank (traceId)? GenTraceId (): traceId; / / put traceId into MDC MDC.put (TRACE_ID, StringUtils.substring (traceId,-MAX_ID_LENGTH));} / * get traceId * / public static String getTraceId () {/ / get String traceId = MDC.get (TRACE_ID) / / if traceId is empty, a new ID return StringUtils.isBlank (traceId) is generated? GenTraceId (): traceId;}}
Add a TraceId filter through WebFilter
Add a GenericFilterBean to get the corresponding value of TraceIdUtils.TRACE_ID from the request header. This value will be taken when the request is initiated by the frontend or passed between micro-services. If not, TraceIdUtils.setTraceId will generate one.
Import org.springframework.core.annotation.Order; import org.springframework.web.filter.GenericFilterBean; @ WebFilter (urlPatterns = "/ *", filterName = "traceIdFilter") @ Order (1) public class TraceIdFilter extends GenericFilterBean {@ Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {/ / traceId initialization HttpServletRequest req = (HttpServletRequest) request; String traceId = req.getHeader (TraceIdUtils.TRACE_ID); TraceIdUtils.setTraceId (traceId) / / execute subsequent filter filterChain.doFilter (request, response);}}
Don't forget to add the @ ServletComponentScan annotation to the startup class of SpringBoot, otherwise the custom Filter will not take effect. Where "com.yourtion.trace.filter" is the name of the package where TraceIdFilter is located.
@ ServletComponentScan (basePackages = "com.yourtion.trace.filter") @ SpringBootApplication public class MyApplication {public static void main (String [] args) {SpringApplication.run (MyApplication.class, args);}}
Add TraceId to Feign
Because @ FeignClient's proxy class uses the RequestInterceptor that uses the Spring context when executing, customize your own interceptor and inject it into the Spring context so that you can add custom request headers to the context of the request.
Import feign.RequestInterceptor; import feign.RequestTemplate; import org.springframework.stereotype.Service; @ Service public class FeignInterceptor implements RequestInterceptor {@ Override public void apply (RequestTemplate template) {template.header (TraceIdUtils.TRACE_ID, TraceIdUtils.getTraceId ());}}
Add TraceId to RestTemplate
Some of the requests are initiated through RestTemplate. Previously, we implemented the configuration class of RestTemplateConfig ourselves, and this time we added it to the relevant configuration:
RestTemplate restTemplate = builder.additionalInterceptors ((request, body, execution)-> {request.getHeaders () .add (TraceIdUtils.TRACE_ID, TraceIdUtils.getTraceId (); return execution.execute (request, body);}) .build ()
At this point, the TraceId addition on the link is complete, and the rest is printed out in the log.
Modify the layout format of Log4j2
Modify the layout format of the log to print out the traceId in MDC:
This is how the micro service shared by Xiaobian implements simple distributed log tracking. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.