Get the App
SLTechnology News&Howtos  ›  Development  › 

How to pass the value of MDC in web application

Shulou Source: shulou.com Published: 2022-06-01 04:51:05 09月11日 Update

This article mainly introduces how to pass the value of MDC in the web application, the article is very detailed, has a certain reference value, interested friends must read it!

Pass the value of MDC

MDC (Mapped Diagnostic Context) is typically used to store specific values for a single task. For example, in a web application, it might store a request id and a user id for each request, making it easier for MDC to find log records related to a single request or the entire user activity.

2017-08-27 14 INFO [server-thread-0] [requestId=060d8c7f, userId=2928ea66] c.g.s.web.Controller-Message.

However, if some part of the code is executed in a dedicated thread pool, the MDC in the thread (the thread that submitted the task) will not continue to be passed. In the following example, the log on line 7 contains "requestId", while the log on line 9 does not:

@ GET@Path ("/ genre/ {name}") @ Produces (MediaType.APPLICATION_JSON) public void getGenre (@ PathParam ("name") String genreName, @ Suspended AsyncResponse response) {try (MDC.MDCCloseable ignored = MDC.putCloseable ("requestId", UUID.randomUUID (). ToString () {String genreId = getGenreIdbyName (genreName) / / Sync call logger.trace ("Submitting task to find genre with id'{}'.", genreId); / / 'requestId' is logged executorService.submit (()-> {logger.trace ("Starting task to find genre with id' {}'.", genreId) / / 'requestId' is not logged Response result = getGenre (genreId) / / Async call .map (artist-> Response.ok (artist) .build ()) .orElseGet (()-> Response.status (Response.Status.NOT_FOUND) .build ()); response.resume (result) );}}

This can be solved through the MDC#getCopyOfContextMap () method:

... public void getGenre (@ PathParam ("name") String genreName, @ Suspended AsyncResponse response) {try (MDC.MDCCloseable ignored = MDC.putCloseable ("requestId", UUID.randomUUID (). ToString () {. Logger.trace ("Submitting task to find genre with id'{}'.", genreId); / / 'requestId' is logged withCopyingMdc (executorService, ()-> {logger.trace ("Starting task to find genre with id' {}', genreId); / / 'requestId' is logged...});}} private void withCopyingMdc (ExecutorService executorService, Runnable function) {Map above is all the content of the article" how to pass MDC values in web applications ". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Applications programs applications logs threads tasks content individual user article storage code value interest can be passed guys partners methods is in more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Huawei Apple macOS Shulou Tech Info