Skip to content

Commit bddac3f

Browse files
authored
[#1015]add x-trace-id to MDC so that can log trace id in logs (#1016)
1 parent 3688755 commit bddac3f

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
4+
~ Copyright (C) 2020-2022 Huawei Technologies Co., Ltd. All rights reserved.
5+
6+
~ Licensed under the Apache License, Version 2.0 (the "License");
7+
~ you may not use this file except in compliance with the License.
8+
~ You may obtain a copy of the License at
9+
~
10+
~ http://www.apache.org/licenses/LICENSE-2.0
11+
~
12+
~ Unless required by applicable law or agreed to in writing, software
13+
~ distributed under the License is distributed on an "AS IS" BASIS,
14+
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
~ See the License for the specific language governing permissions and
16+
~ limitations under the License.
17+
-->
18+
<configuration debug="false">
19+
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
20+
<encoder>
21+
<pattern>%d [%X{x-trace-id}] [%level] [%thread] - %msg (%F:%L\)%n</pattern>
22+
</encoder>
23+
</appender>
24+
25+
<root level="INFO">
26+
<appender-ref ref="STDOUT"/>
27+
</root>
28+
29+
</configuration>

spring-cloud-huawei-common/src/main/java/com/huaweicloud/common/adapters/webmvc/InvocationContextFilter.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
import javax.servlet.http.HttpServletRequest;
2828
import javax.servlet.http.HttpServletResponse;
2929

30+
import org.slf4j.MDC;
31+
3032
import com.huaweicloud.common.configration.dynamic.ContextProperties;
3133
import com.huaweicloud.common.context.InvocationContext;
3234
import com.huaweicloud.common.context.InvocationContextHolder;
@@ -61,12 +63,15 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
6163
context.putContext(InvocationContext.CONTEXT_TRACE_ID, InvocationContext.generateTraceId());
6264
}
6365

66+
// Add MDC
67+
MDC.put(InvocationContext.CONTEXT_TRACE_ID, context.getContext(InvocationContext.CONTEXT_TRACE_ID));
6468
InvocationStage stage = context.getInvocationStage();
6569
stage.begin(buildId((HttpServletRequest) request, context));
6670
try {
6771
chain.doFilter(request, response);
6872
} finally {
6973
stage.finish(((HttpServletResponse) response).getStatus());
74+
MDC.remove(InvocationContext.CONTEXT_TRACE_ID);
7075
}
7176
}
7277

0 commit comments

Comments
 (0)