log4j MDC NDC应用场景

NDC Nested Diagnostic Context )和 MDC Mapped Diagnostic Context )是 log4j 种非常有用的两个类,它们用于存储应用程序的上下文信息( context infomation ),从而便于在 log 中使用这些上下文信息。

 

NDC的实现是用hashtable来存储每个线程的stack信息,这个stack是每个线程可以设置当前线程的request的相关信息,然后当前线 程在处理过程中只要在log4j配置打印出%x的信息,那么当前线程的整个stack信息就会在log4j打印日志的时候也会都打印出来,这样可以很好的 跟踪当前request的用户行为功能。

MDC的实现是使用threadlocal来保存每个线程的Hashtable的类似map的信息,其他功能类似。

 

NDC的实现代码:

 

[java] view plain copy
  1. public   class  NDC {  
  2.   
  3.   
  4.   static  Hashtable ht =  new  Hashtable();  
  5.   
  6.     
  7.   private   static  Stack getCurrentStack() {  
  8.       if  (ht !=  null ) {  
  9.           return  (Stack) ht.get(Thread.currentThread());  
  10.       }  
  11.       return   null ;  
  12.   }  
  13.   
  14.   public   
  15.   static   
  16.   String pop() {  
  17.     Stack stack = getCurrentStack();  
  18.     if (stack !=  null  && !stack.isEmpty())   
  19.       return  ((DiagnosticContext) stack.pop()).message;  
  20.     else   
  21.       return   "" ;  
  22.   }  
  23.   public   
  24.   static   
  25.   String peek() {  
  26.     Stack stack = getCurrentStack();  
  27.     if (stack !=  null  && !stack.isEmpty())  
  28.       return  ((DiagnosticContext) stack.peek()).message;  
  29.     else   
  30.       return   "" ;  
  31.   }  
  32.   public   
  33.   static   
  34.   void  push(String message) {  
  35.     Stack stack = getCurrentStack();  
  36.         
  37.     if (stack ==  null ) {  
  38.       DiagnosticContext dc = new  DiagnosticContext(message,  null );        
  39.       stack = new  Stack();  
  40.       Thread key = Thread.currentThread();  
  41.       ht.put(key, stack);  
  42.       stack.push(dc);  
  43.     } else   if  (stack.isEmpty()) {  
  44.       DiagnosticContext dc = new  DiagnosticContext(message,  null );              
  45.       stack.push(dc);  
  46.     } else  {  
  47.       DiagnosticContext parent = (DiagnosticContext) stack.peek();  
  48.       stack.push(new  DiagnosticContext(message, parent));  
  49.     }      
  50.   }  

MDC的实现:

 

[java] view plain copy
  1. public   class  MDC {  
  2.     
  3.   final   static  MDC mdc =  new  MDC();  
  4.     
  5.   static   final   int  HT_SIZE =  7 ;  
  6.   
  7.   boolean  java1;  
  8.     
  9.   Object tlm;  
  10.   
  11.   private  Method removeMethod;  
  12.   
  13.   private   
  14.   MDC() {  
  15.     java1 = Loader.isJava1();  
  16.     if (!java1) {  
  17.       tlm = new  ThreadLocalMap();  
  18.     }  
  19.   
  20.     try  {  
  21.       removeMethod = ThreadLocal.class .getMethod( "remove" null );  
  22.     } catch  (NoSuchMethodException e) {  
  23.       // don't do anything - java prior 1.5   
  24.     }  
  25.   }  
  26.   
  27.    
  28.    */  
  29.   static   
  30.   public   
  31.   void  put(String key, Object o) {  
  32.      if  (mdc !=  null ) {  
  33.          mdc.put0(key, o);  
  34.      }  
  35.   }  
  36.   
  37.   static    
  38.   public   
  39.   Object get(String key) {  
  40.     if  (mdc !=  null ) {  
  41.         return  mdc.get0(key);  
  42.     }  
  43.     return   null ;  
  44.   }  
  45.   
  46.   static    
  47.   public   
  48.   void  remove(String key) {  
  49.     if  (mdc !=  null ) {  
  50.         mdc.remove0(key);  
  51.     }  
  52.   }  
  53.   
  54.   
  55.   public   static  Hashtable getContext() {  
  56.     if  (mdc !=  null ) {  
  57.         return  mdc.getContext0();  
  58.     } else  {  
  59.         return   null ;  
  60.     }  
  61.   }  
  62.   
  63.   
  64.   public   static   void  clear() {  
  65.     if  (mdc !=  null ) {  
  66.         mdc.clear0();  
  67.     }  
  68.   }  
  69.   
  70.   
  71.   private   
  72.   void  put0(String key, Object o) {  
  73.     if (java1 || tlm ==  null ) {  
  74.       return ;  
  75.     } else  {  
  76.       Hashtable ht = (Hashtable) ((ThreadLocalMap)tlm).get();  
  77.       if (ht ==  null ) {  
  78.         ht = new  Hashtable(HT_SIZE);  
  79.         ((ThreadLocalMap)tlm).set(ht);  
  80.       }      
  81.       ht.put(key, o);  
  82.     }  
  83.   }  
  84.     
  85.   private   
  86.   Object get0(String key) {  
  87.     if (java1 || tlm ==  null ) {  
  88.       return   null ;  
  89.     } else  {         
  90.       Hashtable ht = (Hashtable) ((ThreadLocalMap)tlm).get();  
  91.       if (ht !=  null  && key !=  null ) {  
  92.         return  ht.get(key);  
  93.       } else  {  
  94.         return   null ;  
  95.       }  
  96.     }  
  97.   }  
  98.   
  99.   private   
  100.   void  remove0(String key) {  
  101.     if (!java1 && tlm !=  null ) {  
  102.       Hashtable ht = (Hashtable) ((ThreadLocalMap)tlm).get();  
  103.       if (ht !=  null ) {  
  104.         ht.remove(key);  
  105.         // clean up if this was the last key   
  106.         if  (ht.isEmpty()) {  
  107.           clear0();  
  108.         }  
  109.       }   
  110.     }  
  111.   }  
  112.   
  113.   
  114.   private   
  115.   Hashtable getContext0() {  
  116.      if (java1 || tlm ==  null ) {  
  117.       return   null ;  
  118.     } else  {         
  119.       return  (Hashtable) ((ThreadLocalMap)tlm).get();  
  120.     }  
  121.   }  
  122.   
  123.   private   
  124.   void  clear0() {  
  125.     if (!java1 && tlm !=  null ) {  
  126.       Hashtable ht = (Hashtable) ((ThreadLocalMap)tlm).get();  
  127.       if (ht !=  null ) {  
  128.         ht.clear();  
  129.       }  
  130.       if (removeMethod !=  null ) {  
  131.           // java 1.3/1.4 does not have remove - will suffer from a memory leak   
  132.           try  {  
  133.             removeMethod.invoke(tlm, null );  
  134.           } catch  (IllegalAccessException e) {  
  135.             // should not happen   
  136.           } catch  (InvocationTargetException e) {  
  137.             // should not happen   
  138.           }  
  139.       }  
  140.     }  
  141.   }  
  142.   
  143. }  

在webx框架中对于log4j的MDC的处理:

先配置一个filter,这个filter是放置web.xml的最前面

[java] view plain copy
  1. protected   void  populateMDC(Map<String, String> mdc) {  
  2.     // GET or POST   
  3.     putMDC(mdc, MDC_METHOD, request.getMethod());  
  4.   
  5.       
  6.     StringBuffer requestURL = request.getRequestURL();  
  7.     String queryString = trimToNull(request.getQueryString());  
  8.   
  9.     putMDC(mdc, MDC_REQUEST_URL, getRequestURL(requestURL, null ));  
  10.     putMDC(mdc, MDC_REQUEST_URL_WITH_QUERY_STRING, getRequestURL(requestURL, queryString));  
  11.   
  12.       
  13.     String requestURI = request.getRequestURI();  
  14.     String requestURIWithQueryString = queryString == null  ? requestURI : requestURI +  "?"  + queryString;  
  15.   
  16.     putMDC(mdc, MDC_REQUEST_URI, requestURI);  
  17.     putMDC(mdc, MDC_REQUEST_URI_WITH_QUERY_STRING, requestURIWithQueryString);  
  18.     putMDC(mdc, MDC_QUERY_STRING, queryString);  
  19.   
  20.     // client info   
  21.     putMDC(mdc, MDC_REMOTE_HOST, request.getRemoteHost());  
  22.     putMDC(mdc, MDC_REMOTE_ADDR, request.getRemoteAddr());  
  23.   
  24.     // user agent   
  25.     putMDC(mdc, MDC_USER_AGENT, request.getHeader("User-Agent" ));  
  26.   
  27.     // referrer   
  28.     putMDC(mdc, MDC_REFERRER, request.getHeader("Referer" ));  
  29.   
  30.     // cookies   
  31.     Cookie[] cookies = request.getCookies();  
  32.     List<String> names = emptyList();  
  33.   
  34.     if  (cookies !=  null ) {  
  35.         names = createArrayList(cookies.length);  
  36.   
  37.         for  (Cookie cookie : cookies) {  
  38.             names.add(cookie.getName());  
  39.             putMDC(mdc, MDC_COOKIE_PREFIX + cookie.getName(), cookie.getValue());  
  40.         }  
  41.   
  42.         sort(names);  
  43.     }  
  44.   
  45.     putMDC(mdc, MDC_COOKIES, names.toString());  
  46. }  


在finally中记住cleanMDC,否则可能会造成OOM。

 

[java] view plain copy
  1.    try  {   helper.setLoggingContext();  
  2.   
  3.             chain.doFilter(request, response);  
  4.         } finally  {  
  5.             helper.clearLoggingContext();  
  6.         }  

 

在 NDC 简介部分,我们曾经说过,%x 表示会在每个日志行上打印当前 NDC 上下文。

MDC  %X{remoteAddr}  {remoteAddr} 表示对应map中的remoteAddr的值

配置log4j:

[html] view plain copy
  1. < param   name = "ConversionPattern"   value = "%d{yyyy-MM-dd HH\:mm\:ss} %X{remoteAddr} %X{requestURI} %X{referrer} %X{userAgent} %c %c - %m%n " />   


打 印日志如下:2012-05-22 22:16:30 127.0.0.1 /cta/index.htm Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19 com.alibaba.citrus.webx.impl.WebxRootControllerImpl com.alibaba.citrus.webx.impl.WebxRootControllerImpl - Error occurred while process request /cta/index.htm

 

[html] view plain copy
  1. java.lang.NullPointerException  
  2.     at com.alibaba.citrus.webx.impl.WebxControllerImpl.service(WebxControllerImpl.java:42)  
  3.     at com.alibaba.citrus.webx.impl.WebxRootControllerImpl.handleRequest(WebxRootControllerImpl.java:53)  
  4.     at com.alibaba.citrus.webx.support.AbstractWebxRootController.service(AbstractWebxRootController.java:156)  
  5.     at com.alibaba.citrus.webx.servlet.WebxFrameworkFilter.doFilter(WebxFrameworkFilter.java:141)  
  6.     at com.alibaba.citrus.webx.servlet.FilterBean.doFilter(FilterBean.java:164)  
  7.     at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1322)  
  8.     at com.alibaba.citrus.webx.servlet.SetLoggingContextFilter.doFilter(SetLoggingContextFilter.java:62)  
  9.     at com.alibaba.citrus.webx.servlet.FilterBean.doFilter(FilterBean.java:164)  
  10.     at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1322) 

猜你喜欢

转载自wsmajunfeng.iteye.com/blog/1632028