Mdc-traceid is used in a distributed environment. (The following 3456 classes need to be added in distributed projects, so you can consider adding them to third-party projects and introduce them in POM.)

Because I have encountered the problem of inconvenient log searching in a distributed environment before, although many cloud service environments now provide this function, but in the distributed environment built by myself, I can consider to do this in an emergency, record first, so as to use it quickly next time

1: The introduction of log4J should be careful to remove conflicting packages

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <exclusions> <! > <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> < the groupId > org. Slf4j < / groupId > < artifactId > slf4j - log4j12 < / artifactId > < version > 1.7.21 < / version > < / dependency >

2: Add the configuration file [log4j. XML] to the resources folder

<appender name="trace" class="org.apache.log4j.DailyRollingFileAppender">
    <param name="File" value="D://logs//trace.log"/>
    <param name="DatePattern" value="'.'yyyy-MM-dd"/>
    <param name="threshold" value="info"/>
    <param name="append" value="true"/>
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss.SSS}] - [%X{traceId}] %-6p%c:%L - %m%n"/>
    </layout>
</appender>

<root>
    <level value="info"/>
    <appender-ref ref="trace"/>
</root>

3: Add the [MDCUtils] custom tool class

Public class MDCUtils {/** * [Get traceId] * @return java.lang.String **/ public static String MDC (){RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); HttpServletRequest request = (HttpServletRequest) requestAttributes .resolveReference(RequestAttributes.REFERENCE_REQUEST); String traceId; String traceIdKey = "traceId"; if (request.getHeader(traceIdKey) == null) { traceId = UUID.randomUUID().toString(); } else { traceId = request.getHeader(traceIdKey); } return traceId; }}

4: Add the [LogInterceptor] to each request header to add [traceId]

public class LogInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { String traceIdKey = "traceId"; String traceId = MDCUtils.mdc(); request.setAttribute(traceIdKey, traceId); MDC.clear(); MDC.put(traceIdKey, traceId); return true; }}

5: Register the interceptor

@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LogInterceptor()).addPathPatterns("/test/*"); }}

6: Add request header [traceId] to httpClient for each call to external interface

public class HttpClientHelper { public static String sendGet(String url, LinkedHashMap<String, Object> paramMap, Map < String, Object > headMap) {/ / get a client connection tool CloseableHttpClient httpClient. = HttpClients createDefault (); String entityStr = null; CloseableHttpResponse response = null; */ URIBuilder URIBuilder = new URIBuilder(URL); / / URIBuilder URIBuilder = new URIBuilder(URL); / / URIBuilder URIBuilder = new URIBuilder(URL); /* uribuild.addparameter ("name", "root"); /* uribuild.addparameter ("name", "root"); uriBuilder.addParameter("password", "123456"); */ // the second form of adding parameters // load the parameter if (! CollectionUtils.isEmpty(paramMap)) { List<NameValuePair> paramertersList = new LinkedList<>(); Set<String> keys = paramMap.keySet(); for (String s : keys) { String key = String.valueOf(s); String value = ObjectUtils.isEmpty(paramMap.get(key)) ? null : paramMap.get(key).toString(); if (ObjectUtils.isNotEmpty((value))) { BasicNameValuePair param1 = new BasicNameValuePair(key, value); paramertersList.add(param1); } } uriBuilder.setParameters(paramertersList); } // Build the GET request object from the URI object with parameters HttpGet HttpGet = new HttpGet(uribuild.build ()); if (headMap ! = null) { for (Map.Entry<String, Object> entry : headMap.entrySet()) { if (entry.getValue() ! = null) { httpGet.addHeader(entry.getKey(), entry.getValue().toString()); } } } String traceId = MDC.get("traceId"); httpGet.addHeader("traceId", traceId); httpGet.addHeader("Accept", "*/*"); httpGet.addHeader("Connection", "Keep-Alive"); HttpGet. AddHeader (" user-agent ", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; The rv: 1.7.6) "); HttpGet. AddHeader (" content-type ", "application/x-www-form-urlencoded"); Response = httpclient.execute (httpGet); HttpEntity Entity = Response.getentity (); // Obtain the response entity object HttpEntity = Response.getentity (); EntityStr = entityutils. toString(entity, "utF-8 "); } catch (ClientProtocolException e) {system.err. Println (" THERE is a problem with Http protocol "); e.printStackTrace(); } catch (ParseException e) {system.err. Println (" parse error "); e.printStackTrace(); } catch (URISyntaxException e) {system.err. Println ("URI parsing exception "); e.printStackTrace(); } catch (IOException e) {system.err. Println ("IO exception "); e.printStackTrace(); } finally {// Release the connection if (null! = response) { try { response.close(); httpClient.close(); } catch (IOException e) {system.err. Println (" release connection error "); e.printStackTrace(); } } } return entityStr; } public static String sendPost(String url, LinkedHashMap<String, Object> paramMap, Map<String, Object > headMap) {/ / get a client connection tool CloseableHttpClient httpClient. = HttpClients createDefault (); String entityStr = null; CloseableHttpResponse response = null; Try {// create a POST request object HttpPost HttpPost = new HttpPost(URL); UrlEncodedFormEntity entityParam = null; /* * add request parameter */ // create request parameter if (! CollectionUtils.isEmpty(paramMap)) { List<NameValuePair> paramertersList = new LinkedList<>(); Set<String> keys = paramMap.keySet(); for (String s : keys) { String key = String.valueOf(s); String value = ObjectUtils.isEmpty(paramMap.get(key)) ? null : paramMap.get(key).toString(); if (ObjectUtils.isNotEmpty(value)) { BasicNameValuePair param1 = new BasicNameValuePair(key, value); paramertersList.add(param1); EntityParam = new UrlEncodedFormEntity(paramertersList, "utF-8 "); entityParam = New UrlEncodedFormEntity(paramertersList," utF-8 "); } httpPost.setEntity(entityParam); if (headMap ! = null) { for (Map.Entry<String, Object> entry : headMap.entrySet()) { if (entry.getValue() ! = null) { httpPost.addHeader(entry.getKey(), entry.getValue().toString()); } } } String traceId = MDC.get("traceId"); httpPost.addHeader("traceId", traceId); httpPost.addHeader("Accept", "*/*"); httpPost.addHeader("Connection", "Keep-Alive"); HttpPost. AddHeader (" the user-agent ", "Mozilla / 5.0 (Windows; U; Windows NT 5.1; en-US; The rv: 1.7.6) "); AddHeader (" content-type ", "application/x-www-form-urlencoded"); Response = httpclient.execute (httpPost); HttpEntity Entity = Response.getentity (); // Obtain the response entity object HttpEntity = Response.getentity (); EntityStr = entityutils. toString(entity, "utF-8 "); System.out.println(Arrays.toString(Response.getallheaders ())); } catch (ClientProtocolException e) {system.err. Println (" THERE is a problem with Http protocol "); e.printStackTrace(); } catch (ParseException e) {system.err. Println (" parse error "); e.printStackTrace(); } catch (IOException e) {system.err. Println ("IO exception "); e.printStackTrace(); } finally {// Release the connection if (null! = response) { try { response.close(); httpClient.close(); } catch (IOException e) {system.err. Println (" release connection error "); e.printStackTrace(); } } } return entityStr; }}

7: Request instance: 1- call -2

1: 2021-07-21 11:14:30.168 - [283ba7ba-8910-48E3-8864-cd8de7AF07CB] INFO Com. Example. Demolog4jmdc. Controller. TestController: 27 - test test1 11:14:30. 2021-07-21-169 [283ba7ba-8910-48e3-8864-cd8de7af07cb] INFO com.example.demolog4jmdc.controller.TestService:18 - =====TestService.test1 The 11:14:30 2021-07-21. 169-283 [ba7ba - 8910-48 e3-8864 - cd8de7af07cb] INFO com. Example. Demolog4jmdc. Controller. TestService: 22 - =====TestService. Test3 2021-07-21 11:14:30.169 - [283ba7ba-8910-48E3-8864-cd8de7af07CB] INFO Com. Example. Demolog4jmdc. Controller. TestService: 26 - = = = = = TestService. Test3 11:14:30. 2021-07-21-771 [283ba7ba-8910-48e3-8864-cd8de7af07cb] INFO com.example.demolog4jmdc.controller.TestController:35 - ===s===aaaaa 2: 2021-07-21 11:14:30.746 - [283ba7ba-8910-48E3-8864-cd8de7AF07CB] INFO Com. Example. Demolog4jmdc2. Controller. TestController: 26 - test test1 - traceId: 283 ba7ba - 8910-48 - cd8de7af07cb e3-8864