经典的具有灵活格式的logback layout称为PatternLayout 。和所有layout一样,PatternLayout把一个logging事件转化为一个字符串并返回 。然而,这个返回的字符串如何转换可以通过PatternLayout的pattern模式来调整。
PatternLayout的日志格式化跟C语言中printf()函数的转换模式类似。pattern转换模式是由文本和称为转换标识符的格式控制表达式构成 。每个转换标识符都以百分号’%'开头,后紧接着可选的 “格式修饰符”、“转换字段”或者大括号内的可选参数。“转换字段”最终按转换规则被替代为其他数据字段,比如记录器名称,级别,日期或线程名称。“格式修饰符”控制字段宽度,填充方式、左对齐或右对齐。
例如,一个格式标识符“%-5level{某个参数}”由以下组成:
百分号 | 格式修饰符 | 转换字段 | {某个参数} |
---|---|---|---|
% | -5 | level | {某个参数} |
FileAppender和它的子类需要包含一个encoder。因此,当配置使用FileAppender或者它的子类时, PatternLayout必须包含在一个encoder中。鉴于 FileAppender/ PatternLayout组合如此常见,logback附带一个名为编码器的编码器 PatternLayoutEncoder,其设计仅用于包装PatternLayout实例,以便可以直接解读转换模式pattern。下面是一个具有 PatternLayoutEncoder的ConsoleAppender配置示例:
package chapters.layouts;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.ConsoleAppender;
public class PatternSample {
static public void main(String[] args) throws Exception {
Logger rootLogger = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
LoggerContext loggerContext = rootLogger.getLoggerContext();
// we are not interested in auto-configuration
loggerContext.reset();
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setContext(loggerContext);
encoder.setPattern("%-5level [%thread]: %message%n");
encoder.start();
ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
appender.setContext(loggerContext);
appender.setEncoder(encoder);
appender.start();
rootLogger.addAppender(appender);
rootLogger.debug("Message 1");
rootLogger.warn("Message 2");
}
}
在上面的示例中,转换模式pattern设置为 “%-5level [%thread]:%message%n”。
将在控制台上产生以下输出:
DEBUG [main]:消息1
WARN [main]:消息2
请注意,在转换模式“%-5level [%thread]:%message%n”中,日志的文本和转换标识符之间没有明确的分隔符。解析转换模式时, PatternLayout能够区分文字文本(空格字符,括号,冒号字符)和转换标识符。在上面的示例中,转换标识符%-5level表示日志事件的级别应左对齐,宽度为五个字符。格式说明符将在下面解释。
在PatternLayout中,括号可用于对转换模式进行分组。因此,’(‘和’)'具有特殊含义,如果打算当做文本使用,则需要进行转义。括号的特殊性质将在下面进一步说明。
如前所述,某些转换标识符可能包括大括号{}(用于配置可选参数)。带可选参数的示例转换标识符可以是 %logger{10}。这里“logger”是“转换字段”,10是可选参数。可选参数将在下面进一步讨论。
已识别的“转换字段”及其选项如下表所示。当多个“转换字段”列在同一个表格单元格中时,它们将被视为别名,如下所示:
跳转官网查看下面表格内容
Effect | |||||||||||||||||||||||||
c{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.
Please 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} | 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 | Outputs the name of the logger context to which the logger at the origin of the event was attached to. | ||||||||||||||||||||||||
d{pattern} | 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.
The 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 statement Caller+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} | 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} | 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:
Here are some examples:
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_EVAL returns 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} | 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 | 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} | 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". |