http://logback.qos.ch/manual/mdc.htmlMDC(注意這個類在org.slf4j包里)
基于“多個線程同步處理多個請求”的假設來設計的,上下文信息記錄。
——子線程會自動拷貝雙親線程的這類信息。
——如果沒有附加處理的話,放入線程池處理的任務會丟失MDC上下文。
該設計假定向MDC放數(shù)據(jù)的速度不會太快。
最常用的web場景,是集成在一個servlet的Filter中,在請求時載入MDC信息,doFilter處理完成后卸載MDC信息。
——最好在“驗證用戶”這個Filter之后(或者之中)進行,這樣可以把用戶驗證信息(包括但不限于用戶名)寫入MDC。
交給線程池處理(submit)之前:MDC.getCopyOfContextMap(),把返回的map當作參數(shù)傳給任務線程
線程池處理代碼的第一行:MDC.setContextMapValues(),把接到的map參數(shù)設置到本線程的MDC中(別忘了最后清除掉)
MDCInsertingServletFilter
將web請求常用信息設置到MDC中:
req.remoteHost as returned by the getRemoteHost() method
req.xForwardedFor value of the "X-Forwarded-For" header
req.requestURI as returned by getRequestURI() method
req.requestURL as returned by getRequestURL() method
req.queryString as returned by getQueryString() method
req.userAgent value of the "User-Agent" header
web.xml中的配置
<filter>
<filter-name>MDCInsertingServletFilter</filter-name>
<filter-class>
ch.qos.logback.classic.helpers.MDCInsertingServletFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>MDCInsertingServletFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
注意filter順序,經(jīng)過該filter過濾之后,其它filter才能打印出MDC信息(特別是struts之類依賴filter處理主邏輯的)
使用例子:
%X{req.remoteHost} %X{req.requestURI}%n%d - %m%n
——其實沒多大意義,還是自己寫這個filter,挑選自己的有效信息比較好。