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自定义格式转换器的更多相关文章
- sruts2 自定义类型转换器
1.1.1 Struts2中自定义类型转换器:(了解) 类型转换的过程是双向的过程: JSP---->Action参数提交:String---Date. Action---->JSP ...
- [原创]java WEB学习笔记67:Struts2 学习之路-- 类型转换概述, 类型转换错误修改,如何自定义类型转换器
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- 自定义类型转换器converter
作用:目前将日期转换成string,将string转换成我想要的类型 0509课件里讲 一.数据类型转换在web应用程序中,数据存在两个方向上的转换:1.当提交表单时 表单数据以字符串的形式提交 ...
- Struts入门学习(三)---自定义类型转换器
类型转换器是将浏览器传递的参数进行转换为了与服务器端的参数匹配,先举个例子如果我们想往服务器传递日期类型的参数时我们要怎么让浏览器传过去的让服务器明白 我们新建一个类 ConverterTest.ja ...
- Struts2初学 struts2自定义类型转换器
一.问题的引出 Struts2的类型转换是基于OGNL表达式的,由于请求的参数都是字符串,而JAVA 本身属于强类型的的语言,这样就需要把请求参数字符串转换成其他类型. Struts ...
- springmvc 类型转换器 自定义类型转换器
自定义类型转换器的步骤: 1.定义类型转换器 2.类型转换器的注册(在springmvc配置文件处理) 来解决多种日期格式的问题: springmvc 类型转换器 表单数据填错后返回表单页面(接上面的 ...
- SpringMVC自定义类型转换器
SpringMVC 自定义类型转换器 我们在使用SpringMVC时,常常需要把表单中的参数映射到我们对象的属性中,我们可以在默认的spring-servlet.xml加上如下的配置即可做到普通数据 ...
- 0023SpringMVC自定义类型转换器
页面录入的字符串:2019/12/05可以映射到实体的日期属性上,但是如果是录入2019-12-05就会报错400 bad request,想要以2019-12-05日期格式的方式映射到实体的日期属性 ...
- SpringMVC框架——自定义数据类型转换器
Spring MVC 框架的 Converter<S,T> 是一个可以将一种数据类型转换成另一种数据类型的接口,这里 S 表示源类型,T 表示目标类型. 开发中如果需要自定义数据类型转换时 ...
随机推荐
- 毕业bg(dfs)
毕业bg Time Limit : 2000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other) Total Submissi ...
- SMACSS:一个关于CSS的最佳实践-3.Layout Rules
本篇笔者要介绍的是Layout Rules.看完本篇,大家将会知道Layout Rules的作用,以及哪些CSS应该归类为Layout Rules. 什么是Layout Rules? Layout R ...
- 一般处理程序在VS2012中打开问题
问题:如果你用vs2012建立的一个一般处理程序,运行查看是,出现这样的界面 原因:VS2012默认使用IIS Web服务器,而不是Visual Studio开发服务器,基于安全考虑IIS默认不允许浏 ...
- handlebar.js使用
官方网站:http://handlebarsjs.com/ 下载及查看使用帮助,或者用百度cdn引用 一.定义模板 <script id="entry-template" t ...
- HDU1712-ACboy needs your help
描述: ACboy has N courses this term, and he plans to spend at most M days on study.Of course,the profi ...
- php mysql实现栏目分类递归
header("content-type:text/html;charset=utf-8"); $dbhost = "localhost"; // 数据库主 ...
- vs2012-vs2013编译出来的程序不能在xp上运行解决方法
在链接标志中加入参数: /SUBSYSTEM:WINDOWS,"5.01" 在ide环境下: 项目属性-常规-平台工具集-Visual Studio 2013 - Windows ...
- json对象的封装与解析
一.解析json对象 表结构信息对象,json格式,名称为tableObj * { * "tableName":"t_res", ...
- 第一个Django项目及部署到Sina App Engine
Sina App Engine简称SAE,是个比较好的网站托管平台,目前说是全面免费,其实就是每个人分配很小的资源配额,在一定的使用范围内不用消耗云豆(SAE计费方式),对于个人学习和研究足够了,同类 ...
- ACM—循环小数转变成分数知识点_C++实现
在小学的时候,我们的学生都能把“整数表示成分母是1的分数”,而且大多数学生也都能把有限小数和循环小数表示成分数的形式.这样,整数.分数.有限小数.循环小数都属于有理数.教科书中说“整数和分数统称有理数 ...