logback自定义格式转换器
Posted 沧海一滴
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了logback自定义格式转换器相关的知识,希望对你有一定的参考价值。
创建自定义格式转换符有两步。
首先,必须继承ClassicConverter类。ClassicConverter对象负责从ILoggingEvent 提取
信息,并产生一个字符串。例如,LoggerConverter,它是处理“% logger”转换符的转换器,
它从ILoggingEvent提取logger 的名字并作为字符串返回。
假设我们的自定义ClassicConverter的功能是按照ANSI终端惯例为记录事件的级别进
行着色,下面是一种可能的实现:
示例:样本转换器例子
(src/main/java/chapters/layouts/MySampleConverter.java)
package chapters.layouts; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.pattern.ClassicConverter; import ch.qos.logback.classic.spi.ILoggingEvent; public class MySampleConverter extends ClassicConverter { private static final String END_COLOR = "\\u001b[m"; private static final String ERROR_COLOR = "\\u001b[0;31m"; private static final String WARN_COLOR = "\\u001b[0;33m"; @Override public String convert(ILoggingEvent event) { StringBuffer sbuf = new StringBuffer(); sbuf.append(getColor(event.getLevel())); sbuf.append(event.getLevel()); sbuf.append(END_COLOR); return sbuf.toString(); } /** * Returns the appropriate characters to change the color for the specified * logging level. */ private String getColor(Level level) { switch (level.toInt()) { case Level.ERROR_INT: return ERROR_COLOR; case Level.WARN_INT: return WARN_COLOR; default: return ""; } } }
这里的实现很直观。MySampleConverter类继承ClassicConverter,实现convert方法,
convert方法返回按照ANSI着色编码装饰后的字符串。
第二步,我们必须让logback 知道这个新的Converter。方法是在配置里声明新的转换符。
示例:样本转换器例子
(src/main/java/chapters/layouts/mySampleConverterConfig.xml)
<configuration> <conversionRule conversionWord="sample" converterClass="chapters.layouts.MySampleConverter" /> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%-4relative [%thread] %sample - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root> </configuration>
新的转换符号在配置文件里被声明后,我们可以在PatternLayout模式里像引用任何其
他转换符一样引用它。
由于Windows不支持ANSI终端编码,你可以在其他平台如Linux或Mac上执行看到
效果。
执行:
java chapters.layouts.SampleLogging src/main/java/chapters/layouts/mySampleConverterConfig.xml
输出:
0 [main] DEBUG - Everything\'s going well 3 [main] ERROR - maybe not quite...
请注意“ERROR”是红色的,也正是本例的目的。
这只是基本的,这个方法不好的地方就是要在配置文件里写
<conversionRule conversionWord="sample" converterClass="chapters.layouts.MySampleConverter" />
实际只要模仿logback原生创建的方法把这个转换符加进去就可以了!
ch.qos.logback.classic.PatternLayout.java
package ch.qos.logback.classic; import java.util.HashMap; import ...........; /** * <p> * A flexible layout configurable with pattern string. The goal of this class is * to {@link #format format} a {@link ILoggingEvent} and return the results in a * {#link String}. The format of the result depends on the * <em>conversion pattern</em>. * <p> * For more information about this layout, please refer to the online manual at * http://logback.qos.ch/manual/layouts.html#PatternLayout * */ public class PatternLayout extends PatternLayoutBase<ILoggingEvent> { public static final Map<String, String> defaultConverterMap = new HashMap<String, String>(); public static final String HEADER_PREFIX = "#logback.classic pattern: "; static { defaultConverterMap.putAll(Parser.DEFAULT_COMPOSITE_CONVERTER_MAP); defaultConverterMap.put("d", DateConverter.class.getName()); defaultConverterMap.put("date", DateConverter.class.getName()); defaultConverterMap.put("r", RelativeTimeConverter.class.getName()); defaultConverterMap.put("relative", RelativeTimeConverter.class.getName()); defaultConverterMap.put("level", LevelConverter.class.getName()); defaultConverterMap.put("le", LevelConverter.class.getName()); defaultConverterMap.put("p", LevelConverter.class.getName()); .... }... }
看到没?只要在static块里加入
defaultConverterMap.put("highlight", HighlightingCompositeConverter.class.getName());
map的KEY是转换符,Value是对应的Converter。
这样就不用在配置文件里写RULE了。不过呢……要怎么把这一行加进去呢?嗯……这是个问题。当然我已经找到方法咯。
http://www.cnblogs.com/yhlx/archive/2012/09/25/2701989.html
当然我们也可以自定义过滤器。
实现过程很简单,我们只需要写一个类实现filter接口就OK,里面实现decide()方法。
代码如下:
- package org.linkinpark.commons.logbackLogging;
- import ch.qos.logback.classic.spi.ILoggingEvent;
- import ch.qos.logback.core.filter.Filter;
- import ch.qos.logback.core.spi.FilterReply;
- public class LinkinFilter extends Filter<ILoggingEvent>
- {
- @Override
- public FilterReply decide(ILoggingEvent event)
- {
- if (event.getMessage().contains("LinkinPark"))
- {
- return FilterReply.ACCEPT;
- }
- else
- {
- return FilterReply.DENY;
- }
- }
- }
然后在配置文件中使用到该过滤器的地方配置<filter>就OK了。
- <!-- 控制台输出,生产环境将请stdout去掉 -->
- <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
- <filter class="org.linkinpark.commons.logbackLogging.LinkinFilter" />
- <encoder>
- <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度,%msg:日志消息,%n是换行符 -->
- <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
- </pattern>
- </encoder>
- </appender>
测试代码如下:
- package org.linkinpark.commons.logbackLogging;
- import org.junit.Test;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class LoggingBack
- {
- private static Logger logger = LoggerFactory.getLogger(LoggingBack.class);
- @Test
- public void test()
- {
- logger.debug("LoggingBack.debug()。。。");
- logger.info("LoggingBack.info(LinkinPark)。。。");
- logger.error("LoggingBack.error()。。。");
- }
- }
运行上面的测试,我们来看下控制台输出:
- 10:39:32,945 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
- 10:39:32,945 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
- 10:39:32,945 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [file:/Users/LinkinPark/WorkSpace/linkin-log-test/target/classes/logback.xml]
- 10:39:33,011 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - Setting ReconfigureOnChangeFilter scanning period to 30 seconds
- 10:39:33,012 |-INFO in ReconfigureOnChangeFilter{invocationCounter=0} - Will scan for changes in [[/Users/LinkinPark/WorkSpace/linkin-log-test/target/classes/logback.xml]] every 30 seconds.
- 10:39:33,012 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - Adding ReconfigureOnChangeFilter as a turbo filter
- 10:39:33,014 |-INFO in ch.qos.logback.classic.joran.action.ContextNameAction - Setting logger context name as [Application]
- 10:39:33,014 |-INFO in ch.qos.logback.core.joran.action.TimestampAction - Using context birth as time reference.
- 10:39:33,015 |-INFO in ch.qos.logback.core.joran.action.TimestampAction - Adding property to the context with key="byDay" and value="2016-03-01" to the LOCAL scope
- 10:39:33,016 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
- 10:39:33,018 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]
- 10:39:33,038 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
- 10:39:33,064 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.rolling.RollingFileAppender]
- 10:39:33,066 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE]
- 10:39:33,085 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
- 10:39:33,086 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern log/log-%d{yyyy-MM-dd}.%i.log for the active file
- 10:39:33,088 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@2096442d - The date pattern is \'yyyy-MM-dd\' from file name pattern \'log/log-%d{yyyy-MM-dd}.%i.log\'.
- 10:39:33,088 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@2096442d - Roll-over at midnight.
- 10:39:33,091 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@2096442d - Setting initial period to Tue Mar 01 10:39:13 CST 2016
- 10:39:33,092 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
- 10:39:33,094 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE] - Active log file name: log/LoggingBack-2016-03-01.log
- 10:39:33,094 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE] - File property is set to [log/LoggingBack-2016-03-01.log]
- 10:39:33,095 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.rolling.RollingFileAppender]
- 10:39:33,095 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE-INFO]
- 10:39:33,099 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
- 10:39:33,099 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern log/LOG-INFO-%d{yyyy-MM-dd}.%i.log for the active file
- 10:39:33,100 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@7946e1f4 - The date pattern is \'yyyy-MM-dd\' from file name pattern \'log/LOG-INFO-%d{yyyy-MM-dd}.%i.log\'.
- 10:39:33,100 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@7946e1f4 - Roll-over at midnight.
- 10:39:33,100 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@7946e1f4 - Setting initial period to Tue Mar 01 10:39:13 CST 2016
- 10:39:33,100 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
- 10:39:33,101 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE-INFO] - Active log file name: log/LoggingBack-info.log
- 10:39:33,101 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE-INFO] - File property is set to [log/LoggingBack-info.log]
- 10:39:33,101 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.rolling.RollingFileAppender]
- 10:39:33,101 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE-ERROR]
- 10:39:33,103 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
- 10:39:33,103 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern log/LOG-ERROR-%d{yyyy-MM-dd}.%i.log for the active file
- 10:39:33,103 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@3c09711b - The date pattern is \'yyyy-MM-dd\' from file name pattern \'log/LOG-ERROR-%d{yyyy-MM-dd}.%i.log\'.
- 10:39:33,103 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@3c09711b - Roll-over at midnight.
- 10:39:33,103 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@3c09711b - Setting initial period to Tue Mar 01 10:39:13 CST 2016
- 10:39:33,104 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
- 10:39:33,104 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE-ERROR] - Active log file name: log/LoggingBack-error.log
- 10:39:33,104 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE-ERROR] - File property is set to [log/LoggingBack-error.log]
- 10:39:33,105 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.rolling.RollingFileAppender]
- 10:39:33,105 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [LOGGINGBACK2]
- 10:39:33,106 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
- 10:39:33,106 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern log/LOG-%d{yyyy-MM-dd}.%i.log for the active file
- 10:39:33,106 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@5cc7c2a6 - The date pattern is \'yyyy-MM-dd\' from file name pattern \'log/LOG-%d{yyyy-MM-dd}.%i.log\'.
- 10:39:33,106 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@5cc7c2a6 - Roll-over at midnight.
- 10:39:33,106 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@5cc7c2a6 - Setting initial period to Tue Mar 01 10:18:58 CST 2016
- 10:39:33,107 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
- 10:39:33,107 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[LOGGINGBACK2] - Active log file name: log/LoggingBack2.log
- 10:39:33,107 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[LOGGINGBACK2] - File property is set to [log/LoggingBack2.log]
- 10:39:33,108 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting additivity of logger [org.linkinpark.commons.logbackLogging] to true
- 10:39:33,108 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE] to Logger[org.linkinpark.commons.logbackLogging]
- 10:39:33,108 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE-INFO] to Logger[org.linkinpark.commons.logbackLogging]
- 10:39:33,109 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE-ERROR] to Logger[org.linkinpark.commons.logbackLogging]
- 10:39:33,109 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to DEBUG
- 10:39:33,109 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]
- 10:39:33,109 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
- 10:39:33,109 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@2344fc66 - Registering current configuration as safe fallback point
- 10:39:33.114 [main] INFO o.l.c.logbackLogging.LoggingBack - LoggingBack.info(LinkinPark)。。。
2,log4j.propertites文件转logback.xml文件。
打开logback官网,在左下角有一个在线转log4j的配置文件成logback配置文件的工具,挺好的,我自己尝试过,没问题。
所以以后如果我们原来的项目用的是log4j的日志系统的话想切成logback的话,直接这里转下配置文件,然后代码一行都不用动,挺好的。
在线转文件的地址如下:log4j.prorpertites转成logback.xml文件。
http://blog.csdn.net/u011794238/article/details/50770557
以上是关于logback自定义格式转换器的主要内容,如果未能解决你的问题,请参考以下文章