log4j日誌擴展---自定義PatternLayout

目前擴展log4j的日誌一般使用擴展adaper的方法,這裏使用一種擴展PatternLayout方法.


[java] view plain copy
  1. log4j.rootLogger=debug, stdout, R  
  2.   
  3. log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
  5.   
  6. # Pattern to output the caller's file name and line number.  
  7. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n  
  8.   
  9. log4j.appender.R=org.apache.log4j.RollingFileAppender  
  10. log4j.appender.R.File=example.log  
  11.   
  12. log4j.appender.R.MaxFileSize=100KB  
  13. # Keep one backup file  
  14. log4j.appender.R.MaxBackupIndex=1  
  15.   
  16. log4j.appender.R.layout=org.apache.log4j.PatternLayout  
  17. log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n  

這是log4j官網上的配置

請注意:

[java] view plain copy
  1. log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
  2.   
  3. log4j.appender.R.layout=org.apache.log4j.PatternLayout  

注意到其實這是兩個類

那麼org.apache.log4j.ConsoleAppender可以自定義,思考是否可以自定義log4j.appender.R.layout=org.apache.log4j.PatternLayout

下載官方文件發現有這樣兩個類.

[java] view plain copy
  1. /* 
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more 
  3.  * contributor license agreements.  See the NOTICE file distributed with 
  4.  * this work for additional information regarding copyright ownership. 
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0 
  6.  * (the "License"); you may not use this file except in compliance with 
  7.  * the License.  You may obtain a copy of the License at 
  8.  *  
  9.  *      http://www.apache.org/licenses/LICENSE-2.0 
  10.  *  
  11.  * Unless required by applicable law or agreed to in writing, software 
  12.  * distributed under the License is distributed on an "AS IS" BASIS, 
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  14.  * See the License for the specific language governing permissions and 
  15.  * limitations under the License. 
  16.  */  
  17.   
  18. package examples;  
  19.   
  20. import org.apache.log4j.*;  
  21. import org.apache.log4j.helpers.PatternParser;  
  22.   
  23. /** 
  24.  
  25.   Example showing how to extend PatternLayout to recognize additional 
  26.   conversion characters.   
  27.    
  28.   <p>In this case MyPatternLayout recognizes %# conversion pattern. It 
  29.   outputs the value of an internal counter which is also incremented 
  30.   at each call. 
  31.  
  32.   <p>See <a href=doc-files/MyPatternLayout.java><b>source</b></a> code 
  33.   for more details. 
  34.  
  35.   @see MyPatternParser 
  36.   @see org.apache.log4j.PatternLayout 
  37.   @author Anders Kristensen  
  38. */  
  39. public class MyPatternLayout extends PatternLayout {  
  40.   public  
  41.   MyPatternLayout() {  
  42.     this(DEFAULT_CONVERSION_PATTERN);  
  43.   }  
  44.   
  45.   public  
  46.   MyPatternLayout(String pattern) {  
  47.     super(pattern);  
  48.   }  
  49.       
  50.   public  
  51.   PatternParser createPatternParser(String pattern) {  
  52.     return new MyPatternParser(  
  53.       pattern == null ? DEFAULT_CONVERSION_PATTERN : pattern);  
  54.   }  
  55.     
  56.   public  
  57.   static void main(String[] args) {  
  58.     Layout layout = new MyPatternLayout("[counter=%.10#] - %m%n");  
  59.     Logger logger = Logger.getLogger("some.cat");  
  60.     logger.addAppender(new ConsoleAppender(layout, ConsoleAppender.SYSTEM_OUT));  
  61.     logger.debug("Hello, log");  
  62.     logger.info("Hello again...");      
  63.   }  
  64. }  
  65.    


[java] view plain copy
  1. /* 
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more 
  3.  * contributor license agreements.  See the NOTICE file distributed with 
  4.  * this work for additional information regarding copyright ownership. 
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0 
  6.  * (the "License"); you may not use this file except in compliance with 
  7.  * the License.  You may obtain a copy of the License at 
  8.  *  
  9.  *      http://www.apache.org/licenses/LICENSE-2.0 
  10.  *  
  11.  * Unless required by applicable law or agreed to in writing, software 
  12.  * distributed under the License is distributed on an "AS IS" BASIS, 
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  14.  * See the License for the specific language governing permissions and 
  15.  * limitations under the License. 
  16.  */  
  17.   
  18. package examples;  
  19.   
  20. import org.apache.log4j.helpers.FormattingInfo;  
  21. import org.apache.log4j.helpers.PatternConverter;  
  22. import org.apache.log4j.helpers.PatternParser;  
  23. import org.apache.log4j.spi.LoggingEvent;  
  24.   
  25. /** 
  26.   Example showing how to extend PatternParser to recognize additional 
  27.   conversion characters.  The examples shows that minimum and maximum 
  28.   width and alignment settings apply for "extension" conversion 
  29.   characters just as they do for PatternLayout recognized characters. 
  30.    
  31.   <p>In this case MyPatternParser recognizes %# and outputs the value 
  32.   of an internal counter which is also incremented at each call. 
  33.  
  34.   See <a href=doc-files/MyPatternParser.java><b>source</b></a> code 
  35.    for more details. 
  36.    
  37.   @see org.apache.log4j.examples.MyPatternLayout 
  38.   @see org.apache.log4j.helpers.PatternParser 
  39.   @see org.apache.log4j.PatternLayout 
  40.  
  41.   @author Anders Kristensen  
  42. */  
  43. public class MyPatternParser extends PatternParser {  
  44.   
  45.   int counter = 0;  
  46.   
  47.   public  
  48.   MyPatternParser(String pattern) {  
  49.     super(pattern);  
  50.   }  
  51.       
  52.   public  
  53.   void finalizeConverter(char c) {  
  54.     if (c == '#') {  
  55.       addConverter(new UserDirPatternConverter(formattingInfo));  
  56.       currentLiteral.setLength(0);  
  57.     } else {  
  58.       super.finalizeConverter(c);  
  59.     }  
  60.   }  
  61.     
  62.   private class UserDirPatternConverter extends PatternConverter {  
  63.     UserDirPatternConverter(FormattingInfo formattingInfo) {  
  64.       super(formattingInfo);  
  65.     }  
  66.   
  67.     public  
  68.     String convert(LoggingEvent event) {  
  69.       return String.valueOf(++counter);  
  70.     }  
  71.   }    
  72. }  

直接粘過去找個類測試一下發現是可以使用的,顯示打印日誌的行數


[java] view plain copy
  1. 發現MyPatternLayout基本調用的是父類的方法   

繼續扒

[java] view plain copy
  1. public  
  2.  void finalizeConverter(char c) {  
  3.    if (c == '#') {  
  4.      addConverter(new UserDirPatternConverter(formattingInfo));  
  5.      currentLiteral.setLength(0);  
  6.    } else {  
  7.      super.finalizeConverter(c);  
  8.    }  
  9.  }  


注意看這段代碼


發現字符爲"#"的時候,創建了UserDirPatternConverter 

推薦大家去看PatternParser這裏面有答案


給大家舉個例子


%#{MMMM}

使用extractOption()可以獲得MMMM 

有了MMMM是不是就可以處理很多問題.


想一下,比如我們要在日誌裏面打印公司的編號  orgId


那麼首先配置

[java] view plain copy
  1. log4j.appender.R.layout.ConversionPattern= %#{orgId}  %p %t %c - %m%n  

這樣的話


[java] view plain copy
  1. if (c == '#') {  
  2.             String exs = super.extractOption();  //獲取orgId  
  3.             addConverter(new ExrPatternConverter(formattingInfo, exs));  
  4.             currentLiteral.setLength(0);  
  5.   
  6.         } else {  
  7.             super.finalizeConverter(c);  
  8.         }  



考慮orgId的賦值問題


使用ThreadLocal



故完整的代碼

[java] view plain copy
  1. package com.yogapay.core;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. import org.apache.log4j.helpers.FormattingInfo;  
  7. import org.apache.log4j.helpers.PatternConverter;  
  8. import org.apache.log4j.helpers.PatternParser;  
  9. import org.apache.log4j.spi.LoggingEvent;  
  10.   
  11. public class ExPatternParser extends PatternParser {  
  12.   
  13.     static final ThreadLocal<Map<String, Object>> TH_LOCAL = new ThreadLocal<Map<String, Object>>(){  
  14.         @Override  
  15.         protected HashMap<String, Object> initialValue() {  
  16.             return new HashMap<String, Object>();  
  17.         }   
  18.     };  
  19.   
  20.     public static void setCurrentValue(String key, Object value) {  
  21.         Map<String, Object> map = TH_LOCAL.get();  
  22.         map.put(key, value);  
  23.           
  24.     }  
  25.   
  26.     public ExPatternParser(String pattern) {  
  27.         super(pattern);  
  28.     }  
  29.   
  30.     public void finalizeConverter(char c) {  
  31.         if (c == '#') {  
  32.             String exs = super.extractOption();  
  33.             addConverter(new ExrPatternConverter(formattingInfo, exs));  
  34.             currentLiteral.setLength(0);  
  35.   
  36.         } else {  
  37.             super.finalizeConverter(c);  
  38.         }  
  39.     }  
  40.   
  41.     private class ExrPatternConverter extends PatternConverter {  
  42.   
  43.         private String cfg;  
  44.   
  45.         ExrPatternConverter(FormattingInfo formattingInfo, String cfg) {  
  46.             super(formattingInfo);  
  47.             this.cfg = cfg;  
  48.         }  
  49.   
  50.         public String convert(LoggingEvent event) {  
  51.             Map<String, Object> valueMap = TH_LOCAL.get();  
  52.             if (valueMap != null) {  
  53.                 Object value = valueMap.get(cfg);  
  54.                 if (value != null) {  
  55.                     return String.valueOf(value);  
  56.                 }  
  57.             }  
  58.             return "";  
  59.         }  
  60.     }  
  61. }  


[java] view plain copy
  1. package com.yogapay.core;  
  2.   
  3. import org.apache.log4j.*;  
  4. import org.apache.log4j.helpers.PatternParser;  
  5.   
  6. public class ExPatternLayout extends PatternLayout {  
  7.     public ExPatternLayout() {  
  8.         this(DEFAULT_CONVERSION_PATTERN);  
  9.     }  
  10.   
  11.     public ExPatternLayout(String pattern) {  
  12.         super(pattern);  
  13.     }  
  14.   
  15.         @Override  
  16.     public PatternParser createPatternParser(String pattern) {  
  17.         return new ExPatternParser(pattern == null ? DEFAULT_CONVERSION_PATTERN : pattern);  
  18.     }  
  19. }  


[java] view plain copy
  1. ### set log levels ###  
  2. log4j.rootLogger = info,stdout  
  3.   
  4. ### 輸出到控制檯 ###  
  5. log4j.appender.stdout = org.apache.log4j.ConsoleAppender  
  6. log4j.appender.stdout.Target = System.out  
  7. log4j.appender.stdout.layout = com.yogapay.core.ExPatternLayout  
  8. log4j.appender.stdout.layout.ConversionPattern = lgcNo:%#{orgId} %d{yyyy-MM-dd HH:mm:ss} [%t] %p [%c] - %m%n  

到此擴展完成!


轉載於https://blog.csdn.net/u010162887/article/details/51736637

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章