log4j日志扩展---自定义PatternLayout

本文介绍如何通过扩展PatternLayout来实现自定义的日志格式,包括添加额外的转换字符及利用ThreadLocal变量来记录特定信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目前扩展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.youkuaiyun.com/u010162887/article/details/51736637

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值