您好,登錄后才能下訂單哦!
這篇文章主要介紹在web應(yīng)用程序中如何傳MDC的值,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
傳MDC的值
MDC(Mapped Diagnostic Context)通常用于存儲(chǔ)單個(gè)任務(wù)的特定值。例如,在web應(yīng)用程序中,它可能為每個(gè)請(qǐng)求存儲(chǔ)一個(gè)請(qǐng)求id和一個(gè)用戶id,因此MDC查找與單個(gè)請(qǐng)求或整個(gè)用戶活動(dòng)相關(guān)的日志記錄變得更加容易。
2017-08-27 14:38:30,893 INFO [server-thread-0] [requestId=060d8c7f, userId=2928ea66] c.g.s.web.Controller - Message.
可是如果代碼的某些部分是在專用線程池中執(zhí)行的,則線程(提交任務(wù)的線程)中MDC就不會(huì)被繼續(xù)傳值。在下面的示例中,第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應(yīng)用程序中如何傳MDC的值”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。