Logback Pattern
Logback日志配置示例
<appender name="SYSLOG" class="ch.qos.logback.classic.net.SyslogAppender">
<syslogHost>10.177.81.90</syslogHost>
<facility>local0</facility>
<port>514</port>
<suffixPattern>%date %-5level [%thread] %logger{43}\(%L\) : %msg</suffixPattern>
</appender>
<appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<smtpHost>${MAIL_HOST}</smtpHost>
<smtpPort>${MAIL_PORT}}</smtpPort>
<SSL>true</SSL>
<username>${MAIL_USERNAME}</username>
<password>${MAIL_PASSWORD}</password>
<from>${MAIL_FROM}</from>
<to>${MAIL_TO}</to>
<subject>平台日志报警 [${HOSTNAME}]</subject>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date %-5level %logger{0} - %message%n</pattern>
</layout>
<cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTracker">
<!-- send just one log entry per email -->
<bufferSize>10</bufferSize>
</cyclicBufferTracker>
</appender>
其中SYSLOG的suffixPattern,%date %-5level [%thread] %logger{43}\(%L\) : %msg
, 和EMAIL的layout pattern,%date %-5level %logger{0} - %message%n
,就是配置日志的格式。
Pattern关键字
Conversion Word | Effect |
---|---|
c{length} lo{length} logger{length} | Outputs the name of the logger at the origin of the logging event.This conversion word takes an integer as its first and only option. The converter's abbreviation algorithm will shorten the logger name, usually without significant loss of meaning. Setting the value of length option to zero constitutes an exception. It will cause the conversion word to return the sub-string right to the rightmost dot character in the logger name. The next table provides examples of the abbreviation algorithm in action.Conversion specifierLogger nameResult%loggermainPackage.sub.sample.BarmainPackage.sub.sample.Bar%logger{0}mainPackage.sub.sample.BarBar%logger{5}mainPackage.sub.sample.Barm.s.s.Bar%logger{10}mainPackage.sub.sample.Barm.s.s.Bar%logger{15}mainPackage.sub.sample.Barm.s.sample.Bar%logger{16}mainPackage.sub.sample.Barm.sub.sample.Bar%logger{26}mainPackage.sub.sample.BarmainPackage.sub.sample.BarPlease note that the rightmost segment in a logger name is never abbreviated, even if its length is longer than the length option. Other segments may be shortened to at most a single character but are never removed. |
C{length} class{length} | Outputs the fully-qualified class name of the caller issuing the logging request.Just like the %logger conversion word above, this conversion takes an integer as an option to shorten the class name. Zero carries special meaning and will cause the simple class name to be printed without the package name prefix. By default the class name is printed in full.Generating the caller class information is not particularly fast. Thus, its use should be avoided unless execution speed is not an issue. |
contextName****cn | Outputs the name of the logger context to which the logger at the origin of the event was attached to. |
d{pattern} date{pattern} d{pattern, timezone} date{pattern, timezone} | Used to output the date of the logging event. The date conversion word admits a pattern string as a parameter. The pattern syntax is compatible with the format accepted by java.text.SimpleDateFormat .You can specify the string "ISO8601" for the ISO8601 date format. Note that the %date conversion word defaults to the ISO 8601 date format in the absence of a pattern parameter.Here are some sample parameter values. They assume that the actual date is Friday 20th of October, 2006 and that the author has returned to working on this document just after lunch.Conversion PatternResult%d2006-10-20 14:06:49,812%date2006-10-20 14:06:49,812%date{ISO8601}2006-10-20 14:06:49,812%date{HH:mm:ss.SSS}14:06:49.812%date{dd MMM yyyy;HH:mm:ss.SSS}20 oct. 2006;14:06:49.812The second parameter specifies a timezone. For example, the '%date{HH:mm:ss.SSS, Australia/Perth} would print the time in the time zone of Perth, Australia, the world's most isolated city. Note that in the absence of the timezone parameter, the default timezone of the host Java platform is used. If the specified timezone identifier is unknown or misspelled, the GMT timezone is assumed as dictated by the TimeZone.getTimeZone(String) method specification.COMMON ERROR Given that the comma ',' character is interpreted as the parameter separator, the pattern HH:mm:ss,SSS will be interpreted as the pattern HM:mm:ss and the timezone SSS . If you wish to include a comma in your date pattern, then simply enclose the pattern between quotes. For example, %date{"HH:mm:ss,SSS"}. |
F / file | Outputs the file name of the Java source file where the logging request was issued.Generating the file information is not particularly fast. Thus, its use should be avoided unless execution speed is not an issue. |
caller{depth}caller{depthStart..depthEnd}caller{depth, evaluator-1, ... evaluator-n}****caller{depthStart..depthEnd, evaluator-1, ... evaluator-n} | Outputs location information of the caller which generated the logging event.The location information depends on the JVM implementation but usually consists of the fully qualified name of the calling method followed by the caller's source, the file name and line number between parentheses.A integer can be added to the caller conversion specifier's options to configure the depth of the information to be displayed.For example, %caller{2} would display the following excerpt:0 [main] DEBUG - logging statement Caller+0 at mainPackage.sub.sample.Bar.sampleMethodName(Bar.java:22)Caller+1 at mainPackage.sub.sample.Bar.createLoggingRequest(Bar.java:17) And %caller{3} would display this other excerpt:16 [main] DEBUG - logging statement Caller+0 at mainPackage.sub.sample.Bar.sampleMethodName(Bar.java:22)Caller+1 at mainPackage.sub.sample.Bar.createLoggingRequest(Bar.java:17)Caller+2 at mainPackage.ConfigTester.main(ConfigTester.java:38) A range specifier can be added to the caller conversion specifier's options to configure the depth range of the information to be displayed.For example, %caller{1..2} would display the following excerpt:0 [main] DEBUG - logging statementCaller+0 at mainPackage.sub.sample.Bar.createLoggingRequest(Bar.java:17) This conversion word can also use evaluators to test logging events against a given criterion before computing caller data. For example, using %caller{3, CALLER_DISPLAY_EVAL} will display three lines of stacktrace, only if the evaluator called CALLER_DISPLAY_EVAL returns a positive answer.Evaluators are described below. |
L / line | Outputs the line number from where the logging request was issued.Generating the line number information is not particularly fast. Thus, its use should be avoided unless execution speed is not an issue. |
m / msg / message | Outputs the application-supplied message associated with the logging event. |
M / method | Outputs the method name where the logging request was issued.Generating the method name is not particularly fast. Thus, its use should be avoided unless execution speed is not an issue. |
n | Outputs the platform dependent line separator character or characters.This conversion word offers practically the same performance as using non-portable line separator strings such as "\n", or "\r\n". Thus, it is the preferred way of specifying a line separator. |
p / le / level | Outputs the level of the logging event. |
r / relative | Outputs the number of milliseconds elapsed since the start of the application until the creation of the logging event. |
t / thread | Outputs the name of the thread that generated the logging event. |
X{key:-defaultVal} mdc{key:-defaultVal} | Outputs the MDC (mapped diagnostic context) associated with the thread that generated the logging event.If the mdc conversion word is followed by a key between braces, as in %mdc{userid}, then the MDC value corresponding to the key 'userid' will be output. If the value is null, then the default value specified after the :- operator is output. If no default value is specified than the empty string is output.If no key is given, then the entire content of the MDC will be output in the format "key1=val1, key2=val2".See the chapter on MDC for more details on the subject. |
ex{depth} exception{depth} throwable{depth} ex{depth, evaluator-1, ..., evaluator-n} exception{depth, evaluator-1, ..., evaluator-n} throwable{depth, evaluator-1, ..., evaluator-n} | Outputs the stack trace of the exception associated with the logging event, if any. By default the full stack trace will be output.The throwable conversion word can followed by one of the following options:short: prints the first line of the stack tracefull: prints the full stack traceAny integer: prints the given number of lines of the stack traceHere are some examples:Conversion PatternResult%exmainPackage.foo.bar.TestException: Houston we have a problem at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22) at mainPackage.foo.bar.TestThrower.readyToLaunch(TestThrower.java:17) at mainPackage.ExceptionLauncher.main(ExceptionLauncher.java:38) %ex{short}mainPackage.foo.bar.TestException: Houston we have a problem at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22) %ex{full}mainPackage.foo.bar.TestException: Houston we have a problem at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22) at mainPackage.foo.bar.TestThrower.readyToLaunch(TestThrower.java:17) at mainPackage.ExceptionLauncher.main(ExceptionLauncher.java:38) %ex{2}mainPackage.foo.bar.TestException: Houston we have a problem at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22) at mainPackage.foo.bar.TestThrower.readyToLaunch(TestThrower.java:17) This conversion word can also use evaluators to test logging events against a given criterion before creating the output. For example, using %ex{full, EX_DISPLAY_EVAL} will display the full stack trace of the exception only if the evaluator called EX_DISPLAY_EVALreturns a negative answer. Evaluators are described further down in this document.If you do not specify %throwable or another throwable-related conversion word in the conversion pattern, PatternLayout will automatically add it as the last conversion word, on account of the importance of stack trace information. The $nopex conversion word can be substituted for %throwable, if you do not wish stack trace information to be displayed. See also the %nopex conversion word. |
xEx{depth} xException{depth} xThrowable{depth} xEx{depth, evaluator-1, ..., evaluator-n} xException{depth, evaluator-1, ..., evaluator-n} xThrowable{depth, evaluator-1, ..., evaluator-n} | Same as the %throwable conversion word above with the addition of class packaging information.At the end of each stack frame of the exception, a string consisting of the jar file containing the relevant class followed by the "Implementation-Version" as found in that jar's manifest will be added. This innovative technique was originally suggested by James Strachan. If the information is uncertain, then the class packaging data will be preceded by a tilde, i.e. the '~' character.Here is an example:java.lang.NullPointerException at com.xyz.Wombat(Wombat.java:57) ~[wombat-1.3.jar:1.3] at com.xyz.Wombat(Wombat.java:76) ~[wombat-1.3.jar:1.3] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.5.0_06] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.5.0_06] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.5.0_06] at java.lang.reflect.Method.invoke(Method.java:585) ~[na:1.5.0_06] at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59) [junit-4.4.jar:na] at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:98) [junit-4.4.jar:na] ...etc Logback goes to great lengths to ensure that the class packaging information it displays is correct, even in arbitrarily complex class loader hierarchies. However, when it is unable to guarantee the absolute correctness of the information, then it will prefix the data with a tilde, i.e. the '~' character. Thus, it is theoretically possible for the printed class packaging information to differ from the real class packaging information. So, in the above example, given that packaging data for the Wombat class is preceded by a tilde, it is possible that the correct packaging data is in reality [wombat.jar:1.7].Please note that given its potential cost, computation of packaging data is disabled by default. When computation of packaging data is enabled, PatternLayout will automatically assume the %xThrowable suffix instead of %throwable suffix at the end of the pattern string.Feedback from users indicates that Netbeans chokes on packaging information. |
nopex nopexception | Although it pretends to handle stack trace data, this conversion word does not output any data, thus, effectively ignoring exceptions.The %nopex conversion word allows the user to override PatternLayout 's internal safety mechanism which silently adds the %xThrowable conversion keyword in the absence of another conversion word handling exceptions. |
marker | Outputs the marker associated with the logger request.In case the marker contains children markers, the converter displays the parent as well as childrens' names according to the format shown below.parentName [ child1, child2 ] |
property{key} | Outputs the value associated with a property named key. The the relevant docs on how to define ion entitled define variables and variable scopes. If key is not a property of the logger context, then key will be looked up in the System properties.There is no default value for key. If it is omitted, the returned value will be "Property_HAS_NO_KEY", expliciting the error condition. |
replace(p){r, t} | Replaces occurrences of 'r', a regex, with its replacement 't' in the string produces by the sub-pattern 'p'. For example, "%replace(%msg){'\s', ''}" will remove all spaces contained in the event message.The pattern 'p' can be arbitrarily complex and in particular can contain multiple conversion keywords. For instance, "%replace(%logger %msg){'.', '/'}" will replace all dots in the logger or the message of the event with a forward slash. |
rEx{depth} rootException{depth} rEx{depth, evaluator-1, ..., evaluator-n} rootException{depth, evaluator-1, ..., evaluator-n} | Outputs the stack trace of the exception associated with the logging event, if any. The root cause will be output first instead of the standard "root cause last". Here is a sample output (edited for space):java.lang.NullPointerException at com.xyz.Wombat(Wombat.java:57) ~[wombat-1.3.jar:1.3] at com.xyz.Wombat(Wombat.java:76) ~[wombat-1.3.jar:1.3]Wrapped by: org.springframework.BeanCreationException: Error creating bean with name 'wombat': at org.springframework.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248) [spring-2.0.jar:2.0] at org.springframework.AbstractBeanFactory.getBean(AbstractBeanFactory.java:170) [spring-2.0.jar:2.0] at org.apache.catalina.StandardContext.listenerStart(StandardContext.java:3934) [tomcat-6.0.26.jar:6.0.26] The %rootException converter admits the same optional parameters as the %xException converter described above, including depth and evaluators. It outputs also packaging information. In short, %rootException is very similar to %xException, only the order of exception output is reversed.Tomasz Nurkiewicz, the author of %rootException converter, documents his contribution in a blog entry entitled "Logging exceptions root cause first". |
使用注意项
在pattern中括号"()"有特殊含义,如:%-30(%d{HH:mm:ss.SSS} [%thread]) %-5level %logger{32} - %msg%n
,可以用来表示一个group,然后对这个group设定格式,所以要使用括号的时候需要用反斜杠转义,如:%date %-5level [%thread] %logger{43}\(%L\) : %msg
。
格式设定
格式说明
Format modifier | Left justify | Minimum width | Maximum width | Comment |
---|---|---|---|---|
%20logger | false | 20 | none | Left pad with spaces if the logger name is less than 20 characters long. |
%-20logger | true | 20 | none | Right pad with spaces if the logger name is less than 20 characters long. |
%.30logger | NA | none | 30 | Truncate from the beginning if the logger name is longer than 30 characters. |
%20.30logger | false | 20 | 30 | Left pad with spaces if the logger name is shorter than 20 characters. However, if logger name is longer than 30 characters, then truncate from the beginning. |
%-20.30logger | true | 20 | 30 | Right pad with spaces if the logger name is shorter than 20 characters. However, if logger name is longer than 30 characters, then truncate from the beginning. |
%.-30logger | NA | none | 30 | Truncate from the end if the logger name is longer than 30 characters. |
示例
Format modifier | Logger name | Result |
---|---|---|
[%20.20logger] | main.Name | [ main.Name] |
[%-20.20logger] | main.Name | [main.Name ] |
[%10.10logger] | main.foo.foo.bar.Name | [o.bar.Name] |
[%10.-10logger] | main.foo.foo.bar.Name | [main.foo.f] |
更多
Logback日志颜色设置等更多特性请参考logback layout。
参考
Logback Pattern的更多相关文章
- Logback Pattern 日志格式配置
Logback日志配置示例 <appender name="SYSLOG" class="ch.qos.logback.classic.net.SyslogAppe ...
- 你真的会打 Log 吗
前言 工程师在日常开发工作中,更多的编码都是基于现有系统来进行版本迭代.在软件生命周期中,工程维护的比重也往往过半.当我们维护的系统出现问题时,第一时间想到的是查看日志来判断问题原因,这时候日志记录如 ...
- spring boot 1.x完整学习指南(含各种常见问题servlet、web.xml、maven打包,spring mvc差别及解决方法)
spring boot 入门 关于版本的选择,spring boot 2.0开始依赖于 Spring Framework 5.1.0,而spring 5.x和之前的版本差距比较大,而且应该来说还没有广 ...
- spring-cloud/spring-cloud-sleuth github 项目 mark
97 Star639 Fork335 spring-cloud/spring-cloud-sleuth CodeIssues 5Pull requests 1Projects 0WikiInsigh ...
- 解决java.lang.NoClassDefFoundError: ch/qos/logback/core/joran/spi/Pattern
明明引入了这个,却提示没有 看下面文章: http://www.maocaoying.com/article/109
- LogBack简易教程
1.简介 LogBack是一个日志框架,它与Log4j可以说是同出一源,都出自Ceki Gülcü之手.(log4j的原型是早前由Ceki Gülcü贡献给Apache基金会的) 1.1 LogBac ...
- logback logback.xml常用配置详解 <filter>
<filter>: 过滤器,执行一个过滤器会有返回个枚举值,即DENY,NEUTRAL,ACCEPT其中之一.返回DENY,日志将立即被抛弃不再经过其他过滤器:返回NEUTRAL,有序列表 ...
- logback 常用配置详解<appender>
logback 常用配置详解 <appender> <appender>: <appender>是<configuration>的子节点,是负责写日志的 ...
- logback日志写入数据库(mysql)配置
如题 建议将日志级别设置为ERROR.这样可以避免存储过多的数据到数据中. 1 logback 配置文件(如下) <?xml version="1.0" encoding ...
随机推荐
- android开发艺术探索读书笔记之-------view的事件分发机制
View的点击事件的分发,其实就是对MotionEvent事件的分发过程,即当一个MotionEvent产生后,系统需要把这个事件传递给一个具体的View,而这个过程就是分发过程. 分发过程主要由以下 ...
- [No0000C1]Excel 删除空白行和空白列VBA代码
在exce中删除空行和空列的方法有很多,相对而言删除空行较为简单,只需进行筛选,将空白行筛选出来,删除即可,但要删除空列比较困难.因为你不能按列进行筛选删除.Excel中没有这个功能.当然你可以用另外 ...
- ASP.NET脚本过滤-防止跨站脚本攻击(收集别人的)
ASP.Net 1.1后引入了对提交表单自动检查是否存在XSS(跨站脚本攻击)的能力.当用户试图用<xxxx>之类的输入影响页面返回结果的时候,ASP.Net的引擎会引发一个 HttpRe ...
- @PostConstruct 注解
@PostConstruct 注解 /* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. ...
- 构建微服务(Building Microservices)-PDF 文档
闲时翻译了几篇基于Spring Cloud.Netflix OSS 构建微服务的英文文章,为方便分享交流,整理为PDF文档. PDF 文档目录: 目录 一.微服务操作模型... 3 1. 前提 ...
- 多线程——i++的坑
在使用socket编程的时候发生数据丢失问题,一直以为是网络原因,后来测试后发现是多线程操作同一数据源又未加入数据锁导致. 直接上代码,下面程序执行的结果可能出现198.199.200.两个线程统一时 ...
- RAC OCR盘故障导致的集群重启恢复
一.事故说明 最近出现了一次OCR盘的故障导致Oracle集群件宕机的事故,后以独占模式启动集群,并使用ocr备份恢复了OCR文件以及重新设置了vote disk,然后关闭集群,重启成功. 因此在此处 ...
- Android中的Drawable和动画
Android中Drawable是一种可以在Canvas上进行绘制抽象的概念,种类很多,常见的颜色和图片都可以是一个Drawable.Drawable有很多种,它们表示一种图像的概念,但是它们又不全是 ...
- Chrome 开发工具 Workspace 使用
前端开发中我们经常要在浏览器中做一些细节调整,比如对 CSS 的微调,最快的方式当然是直接在 Chrome 的开发者工具中调整,但问题在于在控制台中调试好的数值我们还需要再在 CSS 源码中再写一次, ...
- 关于js参数传递矛盾新理解
之前看了很多人的解释,说js中,函数的参数传递都是值传递中不理解. 他们无非举了两个例子 在这两个例子中,第二个例子可以看出参数是由值传递的.因为函数内对象的变化没有影响到函数外对象的变化.但是在第一 ...