这篇文章主要介绍在web应用程序中如何传MDC的值,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
传MDC的值
MDC(Mapped Diagnostic Context)通常用于存储单个任务的特定值。例如,在web应用程序中,它可能为每个请求存储一个请求id和一个用户id,因此MDC查找与单个请求或整个用户活动相关的日志记录变得更加容易。
2017-08-27 14:38:30,893 INFO [server-thread-0] [requestId=060d8c7f, userId=2928ea66] c.g.s.web.Controller - Message.
可是如果代码的某些部分是在专用线程池中执行的,则线程(提交任务的线程)中MDC就不会被继续传值。在下面的示例中,第7行的日志中包含“requestId”,而第9行的日志则没有:
@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);
}
);
}
}
这可以通过MDC#getCopyOfContextMap()方法来解决:
...
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
以上是“在web应用程序中如何传MDC的值”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注编程网行业资讯频道!