创建自定义格式转换符有两步。
首先,必须继承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了。不过呢……要怎么把这一行加进去呢?嗯……这是个问题。当然我已经找到方法咯。


 

当然我们也可以自定义过滤器。

 

实现过程很简单,我们只需要写一个类实现filter接口就OK,里面实现decide()方法。

代码如下:

 

1. package org.linkinpark.commons.logbackLogging;  
2.
3. import ch.qos.logback.classic.spi.ILoggingEvent;
4. import ch.qos.logback.core.filter.Filter;
5. import ch.qos.logback.core.spi.FilterReply;
6.
7. public class LinkinFilter extends Filter<ILoggingEvent>
8. {
9.
10. @Override
11. public FilterReply decide(ILoggingEvent event)
12. {
13. if (event.getMessage().contains("LinkinPark"))
14. {
15. return FilterReply.ACCEPT;
16. }
17. else
18. {
19. return FilterReply.DENY;
20. }
21. }
22.
23. }

然后在配置文件中使用到该过滤器的地方配置<filter>就OK了。

 


1. <!-- 控制台输出,生产环境将请stdout去掉 -->  
2. <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
3. <filter class="org.linkinpark.commons.logbackLogging.LinkinFilter" />
4. <encoder>
5. <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度,%msg:日志消息,%n是换行符 -->
6. <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
7. </pattern>
8. </encoder>
9. </appender>

 


测试代码如下:

​1. package org.linkinpark.commons.logbackLogging;  
2.
3. import org.junit.Test;
4. import org.slf4j.Logger;
5. import org.slf4j.LoggerFactory;
6.
7. public class LoggingBack
8. {
9.
10. private static Logger logger = LoggerFactory.getLogger(LoggingBack.class);
11.
12. @Test
13. public void test()
14. {
15. "LoggingBack.debug()。。。");
16. "LoggingBack.info(LinkinPark)。。。");
17. "LoggingBack.error()。。。");
18. }
19.
20. }

 

运行上面的测试,我们来看下控制台输出:

1. 10:39:32,945 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]  
2. 10:39:32,945 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
3. 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]
4. 10:39:33,011 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - Setting ReconfigureOnChangeFilter scanning period to 30 seconds
5. 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.
6. 10:39:33,012 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - Adding ReconfigureOnChangeFilter as a turbo filter
7. 10:39:33,014 |-INFO in ch.qos.logback.classic.joran.action.ContextNameAction - Setting logger context name as [Application]
8. 10:39:33,014 |-INFO in ch.qos.logback.core.joran.action.TimestampAction - Using context birth as time reference.
9. 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. 10:39:33,016 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
11. 10:39:33,018 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]
12. 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
13. 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]
14. 10:39:33,066 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE]
15. 10:39:33,085 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
16. 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
17. 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'.
18. 10:39:33,088 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@2096442d - Roll-over at midnight.
19. 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
20. 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
21. 10:39:33,094 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE] - Active log file name: log/LoggingBack-2016-03-01.log
22. 10:39:33,094 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE] - File property is set to [log/LoggingBack-2016-03-01.log]
23. 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]
24. 10:39:33,095 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE-INFO]
25. 10:39:33,099 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
26. 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
27. 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'.
28. 10:39:33,100 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@7946e1f4 - Roll-over at midnight.
29. 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
30. 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
31. 10:39:33,101 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE-INFO] - Active log file name: log/LoggingBack-info.log
32. 10:39:33,101 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE-INFO] - File property is set to [log/LoggingBack-info.log]
33. 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]
34. 10:39:33,101 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE-ERROR]
35. 10:39:33,103 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
36. 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
37. 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'.
38. 10:39:33,103 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@3c09711b - Roll-over at midnight.
39. 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
40. 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
41. 10:39:33,104 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE-ERROR] - Active log file name: log/LoggingBack-error.log
42. 10:39:33,104 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE-ERROR] - File property is set to [log/LoggingBack-error.log]
43. 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]
44. 10:39:33,105 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [LOGGINGBACK2]
45. 10:39:33,106 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
46. 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
47. 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'.
48. 10:39:33,106 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@5cc7c2a6 - Roll-over at midnight.
49. 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
50. 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
51. 10:39:33,107 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[LOGGINGBACK2] - Active log file name: log/LoggingBack2.log
52. 10:39:33,107 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[LOGGINGBACK2] - File property is set to [log/LoggingBack2.log]
53. 10:39:33,108 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting additivity of logger [org.linkinpark.commons.logbackLogging] to true
54. 10:39:33,108 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE] to Logger[org.linkinpark.commons.logbackLogging]
55. 10:39:33,108 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE-INFO] to Logger[org.linkinpark.commons.logbackLogging]
56. 10:39:33,109 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE-ERROR] to Logger[org.linkinpark.commons.logbackLogging]
57. 10:39:33,109 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to DEBUG
58. 10:39:33,109 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]
59. 10:39:33,109 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
60. 10:39:33,109 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@2344fc66 - Registering current configuration as safe fallback point
61. 10:39:33.114 [main] INFO o.l.c.logbackLogging.LoggingBack - LoggingBack.info(LinkinPark)。。。

OK,只输出了包含我们“LinkinPark”字符串的日志,没问题。

 

2,log4j.propertites文件转logback.xml文件。

打开logback官网,在左下角有一个在线转log4j的配置文件成logback配置文件的工具,挺好的,我自己尝试过,没问题。

所以以后如果我们原来的项目用的是log4j的日志系统的话想切成logback的话,直接这里转下配置文件,然后代码一行都不用动,挺好的。

在线转文件的地址如下:log4j.prorpertites转成logback.xml文件