官方文档:http://logback.qos.ch/manual/index.html logback will try to configure itself using the files logback-test.xml or logback.xml if found on the class path 日志输出级别(level): TRACE < DEBUG < INFO < WARN < ERROR.
配置文件格式: 一、<configuration> 根元素为<configuration> ,包含0或多个<appender>,0或多个<logger>,至多一个<root><configuration>
element, followed by zero or more<appender>
elements, followed by zero or more<logger>
elements, followed by at most one<root>
element
<configurationdebug="true">to print status data
<configurationscan="true"scanPeriod="30 seconds"> 每隔30秒自动扫描配置文件,文件有修改,则加载,未配置scanPeriod,则默认1分钟
二、<logger>
<logger>用于日志输出名称(name)、定义日志的输出级别(level)、输出目的地(appender-ref)、是否继承父<logger>()。
多个logger间中存在继承关系(由name可以看出来),继承关系中根logger用<root>表示
name 决定logger的继承关系:
祖先logger:logger B 以logger A的name+“.”开头,则A 是B的祖先logger
父logger:logger A是logger B的祖先且A与B之间不存在其它的logger.
如果一个<looger>无父<logger>的,则它的父<logger>是<root>.
如:"java" 是"java.util" 父,也是"java.util.Vector"祖先
继承关系对日志输出级别的影响:
子<logger>未定义level,则自动继承父<logger>的level
子<loger>已定义level,则父<logger>的level对子<loger>无效,子<logger>的level可以大于父<logger>
Logger name | Assigned level | Effective level |
---|---|---|
root | DEBUG | DEBUG |
X | INFO | INFO |
X.Y | none | INFO |
X.Y.Z | ERROR | ERROR |
Logger name | Assigned level | Effective level |
---|---|---|
root | ERROR | ERROR |
X | INFO | INFO |
X.Y | DEBUG | DEBUG |
X.Y.Z | WARN | WARN |
继承关系对日志输出目的地的影响:
子logger日志输出目的地:该logger定义的输出目的地Appender,和该logger的祖先中定义的Appender中
Logger Name | Attached Appenders | Additivity Flag | Output Targets | Comment |
---|---|---|---|---|
root | A1 | not applicable | A1 | Since the root logger stands at the top of the logger hierarchy, the additivity flag does not apply to it. |
x | A-x1, A-x2 | true | A1, A-x1, A-x2 | Appenders of "x" and of root. |
x.y | none | true | A1, A-x1, A-x2 | Appenders of "x" and of root. |
x.y.z | A-xyz1 | true | A1, A-x1, A-x2, A-xyz1 | Appenders of "x.y.z", "x" and of root. |
security | A-sec | false | A-sec | No appender accumulation since the additivity flag is set to false . Only appender A-sec will be used. |
security.access | none | true | A-sec | Only appenders of "security" because the additivity flag in "security" is set to
|
logger格式:
<logger name="logger name,可以写包路径(‘.’决定继承关系)" level="TRACE|DEBUG|INFO|WARN|ERROR|OFF|默认继承父Logger日志输出级别" additivity="true/false(默认为true,日志输出目的地:除了该logger定义的输出目的地Appender,还将日志输出到该logger的祖先中定义的Appender中),false:不向祖先中定义的Appender输出"> <appender-ref ref="输出目的地 (AppenderName)" /> </logger> <root level="TRACE|DEBUG|INFO|WARN|ERROR| OFF|默认为DEBUG"> <appender-ref ref="输出目的地 (AppenderName)" /> </root>
三、Appender
ConsoleAppender:
<configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root> </configuration>
FileAppender:
<configuration> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>testFile.log</file> <append>true</append> <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration>
<configuration> <!-- Insert the current time formatted as "yyyyMMdd'T'HHmmss" under the key "bySecond" into the logger context. This value will be available to all subsequent configuration elements. --> <timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss"/> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <!-- use the previously created timestamp to create a uniquely named log file --> <file>log-${bySecond}.txt</file> <encoder> <pattern>%logger{35} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration>
<configuration> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logFile.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover --> <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- keep 30 days' worth of history --> <maxHistory>30</maxHistory> </rollingPolicy> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration>
输出到数据库:
支持的数据库:
RDBMS | tested version(s) | tested JDBC driver version(s) | supports getGeneratedKeys() method | is a dialect provided by logback |
---|---|---|---|---|
DB2 | untested | untested | unknown | NO |
H2 | 1.2.132 | - | unknown | YES |
HSQL | 1.8.0.7 | - | NO | YES |
Microsoft SQL Server | 2005 | 2.0.1008.2 (sqljdbc.jar) | YES | YES |
MySQL | 5.0.22 | 5.0.8 (mysql-connector.jar) | YES | YES |
PostgreSQL | 8.x | 8.4-701.jdbc4 | NO | YES |
Oracle | 10g | 10.2.0.1 (ojdbc14.jar) | YES | YES |
SQLLite | 3.7.4 | - | unknown | YES |
Sybase SQLAnywhere | 10.0.1 | - | unknown | YES |
建表脚本在源码中的路径:
src\main\java\ch\qos\logback\access\db\script
表格式:
he logging_event table contains the following fields:
Field | Type | Description |
---|---|---|
timestamp | big int | The timestamp that was valid at the logging event's creation. |
formatted_message | text | The message that has been added to the logging event, after formatting with
|
logger_name | varchar | The name of the logger used to issue the logging request. |
level_string | varchar | The level of the logging event. |
reference_flag | smallint | This field is used by logback to identify logging events that have an exception or Its value is computed by |
caller_filename | varchar | The name of the file where the logging request was issued. |
caller_class | varchar | The class where the logging request was issued. |
caller_method | varchar | The name of the method where the logging request was issued. |
caller_line | char | The line number where the logging request was issued. |
event_id | int | The database id of the logging event. |
The logging_event_property is used to store the keys and values contained in the MDC
or the Context
. It contains these fields:
Field | Type | Description |
---|---|---|
event_id | int | The database id of the logging event. |
mapped_key | varchar | The key of the MDC property |
mapped_value | text | The value of the MDC property |
The logging_event_exception table contains the following fields:
Field | Type | Description |
---|---|---|
event_id | int | The database id of the logging event. |
i | smallint | The index of the line in the full stack trace. |
trace_line | varchar | The corresponding line |
<configuration> <appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource"> <driverClass>com.mysql.jdbc.Driver</driverClass> <url>jdbc:mysql://host_name:3306/datebase_name</url> <user>username</user> <password>password</password> </connectionSource> </appender> <root level="DEBUG" > <appender-ref ref="DB" /> </root> </configuration>
<configuration debug="true"> <appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.JNDIConnectionSource"> <!-- please note the "java:comp/env/" prefix --> <jndiLocation>java:comp/env/jdbc/logging</jndiLocation> </connectionSource> </appender> <root level="INFO"> <appender-ref ref="DB" /> </root> </configuration>
<configuration> <appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.DataSourceConnectionSource"> <dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource"> <driverClass>com.mysql.jdbc.Driver</driverClass> <jdbcUrl>jdbc:mysql://${serverName}:${port}/${dbName}</jdbcUrl> <user>${user}</user> <password>${password}</password> </dataSource> </connectionSource> </appender> <root level="DEBUG"> <appender-ref ref="DB" /> </root> </configuration>
四、变量定义
方式一:
<configuration> <property name="USER_HOME" value="/home/sebastien" /> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>${USER_HOME}/myApp.log</file> <encoder> <pattern>%msg%n</pattern> </encoder> </appender> <root level="debug"> <appender-ref ref="FILE" /> </root> </configuration>
方式二:
<configuration>
<property resource="resource1.properties" />
<!--resource1.properties 需要在类路径中/resource1.properties-->
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>${USER_HOME}/myApp.log</file>
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="FILE" />
</root>
</configuration>
方式三: 通过脚本或程序设置变量值 1.在启动shell 中设置环境变量:export USER_HOME=变量值 2.在java logback初始化之前 设置 System.setProperty("USER_HOME",变量值); <configuration> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>${USER_HOME}/myApp.log</file> <encoder> <pattern>%msg%n</pattern> </encoder> </appender> <root level="debug"> <appender-ref ref="FILE" /> </root> </configuration>
五、PatternLayout
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.
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} 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 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 | ||||||||||||||||||||||||
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{depth, 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) 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 valuespecified 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:
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. | ||||||||||||||||||||||||
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. If you do not specify %xThrowable or another throwable-related conversion word in the conversion pattern, 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]. Feedback from users indicates that Netbeans chokes on packaging information. If you are a Netbeans user, then you should disable packaging information in stack traces by adding "%ex" at the end of of your conversion pattern. For example, "%d %logger - %m%n" should be rewritten as "%d %logger - %m%n%ex" | ||||||||||||||||||||||||
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 | ||||||||||||||||||||||||
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 keywill 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". |