问题描述
我们正在使用:
- Spring Boot
- Slf4J
- 登录
- ELK堆栈
现在,我们要使用MDC
将POST请求JSON中提供的唯一跟踪号添加到给定请求的每个日志语句中.
Now we want to use MDC
to add the unique tracking number, which is provided in the POST request JSON, to every log statement for a given request.
我用Google搜索了一些博客文章,这些文章对我没有多大用处.
I googled some blog posts, those are not useful for me much.
下面是我们正在使用的logback.xml
Below is the logback.xml
which we are using
<configuration>
<property name="PROJECT_ID" value="template-api"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="net.logstash.logback.encoder.LogstashEncoder"/>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
任何人都可以提供有关如何完成此操作的帮助吗?
Can anyone provide some help on how to get this done please?
推荐答案
您可以使用Logback的已映射诊断上下文,以向每个日志消息传播唯一的跟踪号.
You can use Logback's Mapped Diagnotic Context to propagate a unique tracking number to every log message.
这有两部分:
-
将您唯一的跟踪号码放入MDC,例如
MDC.put("uniqueTrackingNumber", the_unique_tracking_number);
在您的日志语句中包括MDC条目.您可以通过在日志记录模式中指定它来执行此操作.因此,如果将唯一的跟踪号存储在名为uniqueTrackingNumber
的MDC条目中,则可以通过定义如下布局来将其包括在发出的日志事件中:
Include the MDC entry in your log statements. You do this by specifying it in your logging pattern. So, if you store the unique tracking number in a MDC entry named uniqueTrackingNumber
then you would include it in your emitted log events by defining a layout like this:
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} [%thread] [%X{uniqueTrackingNumber}] %-5level %logger{36} - %msg%n
</Pattern>
</layout>
更多详细信息在文档中.
我认为唯一跟踪号"的范围仅限于请求(或通过您的应用程序的单个流")?如果是这样,那么您将想要确定一些油门点,可以在其中推入MDC值.在Spring Boot的世界中,这很可能是Filter
.可能是这样的:
I presume that the scope of a "unique tracking number" is limited to a request (or a single 'flow' through your application)? If so, then you'll want to identify some throttle point where you can push the MDC value on the way in. In the Spring Boot world this is likely to be a Filter
. Something like this, perhaps:
@Component
public static class UniqueTrackingNumberFilter extends OncePerRequestFilter() {
@Override
protected abstract void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// presumably this is extracted from the request (or defaulted, if not supplied)
int uniqueTrackingNumber = ;
MDC.put("uniqueTrackingNumber", uniqueTrackingNumber);
}
}
或者,您可以扩展Logback的 MDCInsertingServletFilter
以提取所需的内容从请求中并将其推送到MDC.
Alternatively you could extend Logback's MDCInsertingServletFilter
to extract whatever you want from the request and push it into MDC.
这篇关于如何在Spring Boot中使用logback和SLF4J的MDC来捕获POST请求json中的唯一跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!