logback-spring.xmlhtml
<?xml version="1.0" encoding="UTF-8"?> <configuration> <!-- <pattern> %d{yyyy-MM-dd HH:mm:ss} [%level] - %msg%n Logger: %logger Class: %class File: %file Caller: %caller Line: %line Message: %m Method: %M Relative: %relative Thread: %thread Exception: %ex xException: %xEx nopException: %nopex rException: %rEx Marker: %marker newline:%n </pattern> --> <property name="CUSTOM_LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread]%logger -%msg%n"/> <include resource="org/springframework/boot/logging/logback/base.xml"/> <appender name="ROLLING-FILE-INFO" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logs/todo.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover --> <fileNamePattern>logs/todo.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- keep 30 days' worth of history capped at 1GB total size --> <maxHistory>30</maxHistory> <totalSizeCap>1GB</totalSizeCap> </rollingPolicy> <encoder> <pattern>${CUSTOM_LOG_PATTERN}</pattern> </encoder> </appender> <appender name="ROLLING-FILE-WARN" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logs/todo-warn.log</file> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>WARN</level> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover --> <fileNamePattern>logs/todo-warn.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- keep 30 days' worth of history capped at 5GB total size --> <maxHistory>30</maxHistory> <totalSizeCap>5GB</totalSizeCap> </rollingPolicy> <encoder> <pattern>${CUSTOM_LOG_PATTERN}</pattern> </encoder> </appender> <logger name="com.tangcheng" level="INFO"> <appender-ref ref="ROLLING-FILE-WARN"/> </logger> <logger name="org" level="INFO"> <appender-ref ref="ROLLING-FILE-WARN"/> </logger> <root level="INFO"> <appender-ref ref="ROLLING-FILE-INFO"/> </root> </configuration>
In the remainder of this document, we will write "logback" to refer to the logback-classic module.
Logger, Appenders and Layouts
Logback is built upon three main classes: Logger, Appender and Layout.
These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported.
The Logger class is part of the logback-classic module.
On the other hand, the Appender and Layout interfaces are part of logback-core.
As a general-purpose module, logback-core has no notion of loggers.java
Example: Additivity flag (logback-examples/src/main/resources/chapters/configuration/additivityFlag.xml)git
<configuration> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>foo.log</file> <encoder> <pattern>%date %level [%thread] %logger{10} [%file : %line] %msg%n</pattern> </encoder> </appender> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%msg%n</pattern> </encoder> </appender> <logger name="chapters.configuration.Foo" additivity="false"> <appender-ref ref="FILE" /> </logger> <root level="debug"> <appender-ref ref="STDOUT" /> </root> </configuration>
This example, the appender named FILE is attached to the chapters.configuration.Foo logger. Moreover, the chapters.configuration.Foo logger has its additivity flag set to false such that its logging output will be sent to the appender named FILE but not to any appender attached higher in the hierarchy. Other loggers remain oblivious to the additivity setting of the chapters.configuration.Foo logger.
Running the MyApp3 application with the additivityFlag.xml configuration file will output results on the console from the chapters.configuration.MyApp3 logger.
However, output from the chapters.configuration.Foo logger will appear in the foo.log file and only in that file.github
https://logback.qos.ch/manual/configuration.htmlweb
Joran supports including parts of a configuration file from another file. This is done by declaring a <include>
element, as shown below:算法
Example: File include (logback-examples/src/main/resources/chapters/configuration/containingConfig.xml)spring
<configuration> <include file="src/main/java/chapters/configuration/includedConfig.xml"/> <root level="DEBUG"> <appender-ref ref="includedConsole" /> </root> </configuration>
The target file MUST have its elements nested inside an <included>
element. For example, a ConsoleAppender
could be declared as:數據庫
Example: File include (logback-examples/src/main/resources/chapters/configuration/includedConfig.xml)express
<included> <appender name="includedConsole" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>"%d - %m%n"</pattern> </encoder> </appender> </included>
Again, please note the mandatory <included>
element.apache
The contents to include can be referenced as a file, as a resource, or as a URL.
As a resource:
To include a resource, i.e a file found on the class path, use the resource attribute.
<include resource="includedConfig.xml"/>
As a URL:
To include the contents of a URL use the url attribute.
<include url="http://some.host.com/includedConfig.xml"/>
If it cannot find the file to be included, logback will complain by printing a status message. In case the included file is optional, you can suppress the warning message by setting optional attribute to true
in the <include>
element.
<include optional="true" ..../>
Appender Additivity
The output of a log statement of logger L will go to all the appenders in L and its ancestors. This is the meaning of the term "appender additivity".
However, if an ancestor of logger L, say P, has the additivity flag set to false, then L's output will be directed to all the appenders in L and its ancestors up to and including P but not the appenders in any of the ancestors of P.
Loggers have their additivity flag set to true by default.
The table below shows an example:
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 false . |
More often than not, users wish to customize not only the output destination but also the output format. This is accomplished by associating a layout with an appender. The layout is responsible for formatting the logging request according to the user's wishes, whereas an appender takes care of sending the formatted output to its destination. ThePatternLayout
, part of the standard logback distribution, lets the user specify the output format according to conversion patterns similar to the C language printf
function.
The following two lines will yield the exact same output. However, in case of a disabled logging statement, the second variant will outperform the first variant by a factor of at least 30.
logger.debug("The new entry is "+entry+".");
logger.debug("The new entry is {}.", entry);
https://logback.qos.ch/manual/architecture.html
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. |
Below are various format modifier examples for the logger conversion specifier.
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. |
The table below list examples for format modifier truncation. Please note that the square brackets, i.e the pair of "[]" characters, are not part of the output. They are used to delimit the width of output.
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]
|
https://logback.qos.ch/manual/layouts.html
spring boot中使用logback時一個一個配置文件示例:
簡單的:
logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration> <include resource="org/springframework/boot/logging/logback/base.xml" /> <logger name="sample.logback" level="DEBUG" /> <springProfile name="staging"> <logger name="sample.logback" level="TRACE" /> </springProfile> </configuration>
include語句利用了spring boot中默認的logback中的一些配置。有些引用,能夠不用定義名字爲STDOUT和File的appender,不用定義Root節點
在spring boot中使用logback,可使用profile的設定。在不一樣的環境,使用不一樣的logger定義。
若是使用maven的Filter插件,也能夠在logback-spring.xml中引用相關變量,package後也會替換,由於maven Filter插件會替換classpath下相關文件中與之匹配的 標識位
小結:就上面的需求,不建議使用spring-logback.xml配置文件,直接在application.yml(或application.properties)文件中定義便可
示例:
logging:
level:
org.springframework.web: ERROR
com.demo: DEBUG
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} - %msg%n"
file: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
file: logs/application.log
若是要將error日誌和info日誌分開輸出,就須要自定義appender
<?xml version="1.0" encoding="UTF-8"?> <configuration> <property name="CUSTOM_LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread]%logger -%msg%n"/> <include resource="org/springframework/boot/logging/logback/base.xml"/> <appender name="ROLLING-FILE-INFO" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logs/whatif.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover --> <fileNamePattern>logs/whatif.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- 保留30天的歷史日誌 --> <maxHistory>30</maxHistory> </rollingPolicy> <encoder> <pattern>${CUSTOM_LOG_PATTERN}</pattern> </encoder> </appender> <appender name="ROLLING-FILE-WARN" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logs/whatif-warn.log</file> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>WARN</level> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover --> <fileNamePattern>logs/whatif-warn.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- 保留30天的歷史日誌 --> <maxHistory>30</maxHistory> </rollingPolicy> <encoder> <pattern>${CUSTOM_LOG_PATTERN}</pattern> </encoder> </appender> <logger name="com.tang" level="WARN"> <appender-ref ref="ROLLING-FILE-WARN"/> </logger> <logger name="com.tang" level="INFO"> <appender-ref ref="ROLLING-FILE-INFO"/> </logger> <root level="INFO"> <appender-ref ref="ROLLING-FILE-INFO"/> </root> </configuration>
上面的定義方法,會致使com.tang這個package的info及以上級別的log會在 ROLLING-FILE-INFO appender中打印兩遍。即紅色加粗的logger配置是不須要的,刪除便可
選定義root,再定義某個package下的log打印,是一種 「先禁止全部,再容許個別」的配置方法,即「除了xxx,其它的都要xxx作
生成的日誌文件:
一:根節點<configuration>包含的屬性: scan: 當此屬性設置爲true時,配置文件若是發生改變,將會被從新加載,默認值爲true。 scanPeriod: 設置監測配置文件是否有修改的時間間隔,若是沒有給出時間單位,默認單位是毫秒。當scan爲true時,此屬性生效。默認的時間間隔爲1分鐘。 debug: 當此屬性設置爲true時,將打印出logback內部日誌信息,實時查看logback運行狀態。默認值爲false。 例如: <configuration scan="true" scanPeriod="60 seconds" debug="false"> <!-- 其餘配置省略--> </configuration> 2.1設置上下文名稱:<contextName> 每一個logger都關聯到logger上下文,默認上下文名稱爲「default」。但可使用<contextName>設置成其餘名字,用於區分不一樣應用程序的記錄。一旦設置,不能修改。 <configuration scan="true" scanPeriod="60 seconds" debug="false"> <contextName>myAppName</contextName> <!-- 其餘配置省略--> </configuration> 2.2設置變量: <property> 用來定義變量值的標籤,<property> 有兩個屬性,name和value;其中name的值是變量的名稱,value的值時變量定義的值。經過<property>定義的值會被插入到logger上下文中。定義變量後,可使「${}」來使用變量。 例如使用<property>定義上下文名稱,而後在<contentName>設置logger上下文時使用。 <configuration scan="true" scanPeriod="60 seconds" debug="false"> <property name="APP_Name" value="myAppName" /> <contextName>${APP_Name}</contextName> <!-- 其餘配置省略--> </configuration> 2.3設置loger: <loger> 用來設置某一個包或者具體的某一個類的日誌打印級別、以及指定<appender>。<loger>僅有一個name屬性,一個可選的level和一個可選的addtivity屬性。 name: 用來指定受此loger約束的某一個包或者具體的某一個類。 level: 用來設置打印級別,大小寫無關:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,還有一個特俗值INHERITED或者同義詞NULL,表明強制執行上級的級別。 若是未設置此屬性,那麼當前loger將會繼承上級的級別。 addtivity: 是否向上級loger傳遞打印信息。默認是true。會在Root中打印。若是root也引用了自定義logger中引用過的appender,則Root就會打印兩份信息到appender <loger>能夠包含零個或多個<appender-ref>元素,標識這個appender將會添加到這個loger。 <root> 也是<loger>元素,可是它是根loger。只有一個level屬性,應爲已經被命名爲"root". level: 用來設置打印級別,大小寫無關:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,不能設置爲INHERITED或者同義詞NULL。 默認是DEBUG。 <root>能夠包含零個或多個<appender-ref>元素,標識這個appender將會添加到這個loger。
spring boot默認配置的logback中的信息:
default.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- Default logback configuration provided for import, equivalent to the programmatic initialization performed by Boot --> <included> <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" /> <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" /> <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" /> <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/> <property name="FILE_LOG_PATTERN" value="${FILE_LOG_PATTERN:-%d{yyyy-MM-dd HH:mm:ss.SSS} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/> <appender name="DEBUG_LEVEL_REMAPPER" class="org.springframework.boot.logging.logback.LevelRemappingAppender"> <destinationLogger>org.springframework.boot</destinationLogger> </appender> <logger name="org.apache.catalina.startup.DigesterFactory" level="ERROR"/> <logger name="org.apache.catalina.util.LifecycleBase" level="ERROR"/> <logger name="org.apache.coyote.http11.Http11NioProtocol" level="WARN"/> <logger name="org.apache.sshd.common.util.SecurityUtils" level="WARN"/> <logger name="org.apache.tomcat.util.net.NioSelectorPool" level="WARN"/> <logger name="org.eclipse.jetty.util.component.AbstractLifeCycle" level="ERROR"/> <logger name="org.hibernate.validator.internal.util.Version" level="WARN"/> <logger name="org.springframework.boot.actuate.endpoint.jmx" additivity="false"> <appender-ref ref="DEBUG_LEVEL_REMAPPER"/> </logger> </included>
console-appender.xml 會引用default.xmk中定義的屬性
<?xml version="1.0" encoding="UTF-8"?> <!-- Console appender logback configuration provided for import, equivalent to the programmatic initialization performed by Boot --> <included> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>${CONSOLE_LOG_PATTERN}</pattern> <charset>utf8</charset> </encoder> </appender> </included>
file-appender.xml會引用default.xmk中定義的屬性
<?xml version="1.0" encoding="UTF-8"?> <!-- File appender logback configuration provided for import, equivalent to the programmatic initialization performed by Boot --> <included> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <encoder> <pattern>${FILE_LOG_PATTERN}</pattern> </encoder> <file>${LOG_FILE}</file> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <fileNamePattern>${LOG_FILE}.%i</fileNamePattern> </rollingPolicy> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>10MB</MaxFileSize> </triggeringPolicy> </appender> </included>
base.xml屬於集上面於大成者,引用上面的default.xml,file-appender.xml,console-appender.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- Base logback configuration provided for compatibility with Spring Boot 1.1 --> <included> <include resource="org/springframework/boot/logging/logback/defaults.xml" /> <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/spring.log}"/> <include resource="org/springframework/boot/logging/logback/console-appender.xml" /> <include resource="org/springframework/boot/logging/logback/file-appender.xml" /> <root level="INFO"> <appender-ref ref="CONSOLE" /> <appender-ref ref="FILE" /> </root> </included>
由於spring boot 中已經定義,因此在logback-spring.xml中能夠不用定義
=====================================================finish=====================================================
報錯:
java.lang.IllegalStateException: Logback configuration error detected: ERROR in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Filename pattern [logs/log.%d{yyyy-MM-dd}_%i.log] contains an integer token converter, i.e. %i, INCOMPATIBLE with this configuration. Remove it. ERROR in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Filename pattern [logs/log-warn.%d{yyyy-MM-dd}_%i.log] contains an integer token converter, i.e. %i, INCOMPATIBLE with this configuration. Remove it. at org.springframework.boot.logging.logback.LogbackLoggingSystem.loadConfiguration(LogbackLoggingSystem.java:152) at org.springframework.boot.logging.AbstractLoggingSystem.initializeWithConventions(AbstractLoggingSystem.java:72) at org.springframework.boot.logging.AbstractLoggingSystem.initialize(AbstractLoggingSystem.java:50) at org.springframework.boot.logging.logback.LogbackLoggingSystem.initialize(LogbackLoggingSystem.java:106)
解決辦法:
將日誌文件格式中的"%i"去掉。由於TimeBasedRollingPolicy是按日期分隔文件的,不須要這個%i,這個按文件大小分隔文件時纔會使用。
若是使用ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"策略時,就須要這個%i了
eg:
<configuration> <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>mylog.txt</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <!-- rollover daily --> <fileNamePattern>mylog-%d{yyyy-MM-dd}.%i.txt</fileNamePattern> <!-- each file should be at most 100MB, keep 60 days worth of history, but at most 20GB --> <maxFileSize>100MB</maxFileSize> <maxHistory>60</maxHistory> <totalSizeCap>20GB</totalSizeCap> </rollingPolicy> <encoder> <pattern>%msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="ROLLING" /> </root> </configuration>
Note the "%i" conversion token in addition to "%d". Both the %i and %d tokens are mandatory.
Each time the current log file reaches maxFileSize before the current time period ends, it will be archived with an increasing index, starting at 0.
Size and time based archiving supports deletion of old archive files.
You need to specify the number of periods to preserve with the maxHistory property.
When your application is stopped and restarted, logging will continue at the correct location, i.e. at the largest index number for the current period.
http://mcs.une.edu.au/doc/logback/manual/appenders.html
Declaring project dependencies for logging
Given Maven's transitive dependency rules, for "regular" projects (not libraries or frameworks) declaring logging dependencies can be accomplished with a single dependency declaration.
LOGBACK-CLASSIC(須要slf4j-api和logback-classic)
If you wish to use logback-classic as the underlying logging framework, all you need to do is to declare "ch.qos.logback:logback-classic" as a dependency in your pom.xml file as shown below. In addition to logback-classic-1.0.13.jar, this will pull slf4j-api-1.7.25.jar as well as logback-core-1.0.13.jar into your project. Note that explicitly declaring a dependency on logback-core-1.0.13 or slf4j-api-1.7.25.jar is not wrong and may be necessary to impose the correct version of said artifacts by virtue of Maven's "nearest definition" dependency mediation rule.
<dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.0.13</version> </dependency>
LOG4J(須要slf4j-log4j12這個jar)
If you wish to use log4j as the underlying logging framework, all you need to do is to declare "org.slf4j:slf4j-log4j12" as a dependency in your pom.xml file as shown below. In addition to slf4j-log4j12-1.7.25.jar, this will pull slf4j-api-1.7.25.jar as well as log4j-1.2.17.jar into your project. Note that explicitly declaring a dependency on log4j-1.2.17.jar or slf4j-api-1.7.25.jar is not wrong and may be necessary to impose the correct version of said artifacts by virtue of Maven's "nearest definition" dependency mediation rule.
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency>
JAVA.UTIL.LOGGING(須要slf4j-jdk14這個jar)
If you wish to use java.util.logging as the underlying logging framework, all you need to do is to declare "org.slf4j:slf4j-jdk14" as a dependency in your pom.xml file as shown below. In addition to slf4j-jdk14-1.7.25.jar, this will pull slf4j-api-1.7.25.jar into your project. Note that explicitly declaring a dependency on slf4j-api-1.7.25.jar is not wrong and may be necessary to impose the correct version of said artifact by virtue of Maven's "nearest definition" dependency mediation rule.
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-jdk14</artifactId> <version>1.7.25</version> </dependency>
Binary com
https://www.slf4j.org/manual.html
例如:%-4relative 表示,將輸出從程序啓動到建立日誌記錄的時間 進行左對齊 且最小寬度爲4
格式修飾符,與轉換符共同使用:
可選的格式修飾符位於「%」和轉換符之間。
第一個可選修飾符是左對齊 標誌,符號是減號「-」;
接着是可選的最小寬度 修飾符,用十進制數表示。若是字符小於最小寬度,則左填充或右填充,默認是左填充(即右對齊),填充符爲空格。若是字符大於最小寬度,字符永遠不會被截斷。最大寬度 修飾符,符號是點號"."後面加十進制數。若是字符大於最大寬度,則從前面截斷。點符號「.」後面加減號「-」在加數字,表示從尾部截斷。
2016-07-04 07:37:29.801 [restartedMain] INFO o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'configurationPropertiesRebinderAutoConfiguration' of type [class org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$97204b4c] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2016-07-04 07:37:30.482 [restartedMain] ERROR org.springframework.boot.SpringApplication - Application startup failed java.lang.IllegalStateException: Logback configuration error detected: ERROR in ch.qos.logback.core.rolling.RollingFileAppender[FILE] - Appender [FILE] failed to append. java.lang.NullPointerException ERROR in c.q.l.c.recovery.ResilientFileOutputStream@403418161 - IO failure while writing to file [demo.log] java.io.IOException: Stream Closed at org.springframework.boot.logging.logback.LogbackLoggingSystem.loadConfiguration(LogbackLoggingSystem.java:151) at org.springframework.boot.logging.AbstractLoggingSystem.initializeWithConventions(AbstractLoggingSystem.java:71) at org.springframework.boot.logging.AbstractLoggingSystem.initialize(AbstractLoggingSystem.java:49) at org.springframework.boot.logging.logback.LogbackLoggingSystem.initialize(LogbackLoggingSystem.java:106) at org.springframework.boot.logging.LoggingApplicationListener.initializeSystem(LoggingApplicationListener.java:301) at org.springframework.boot.logging.LoggingApplicationListener.initialize(LoggingApplicationListener.java:253) at org.springframework.boot.logging.LoggingApplicationListener.onApplicationEnvironmentPreparedEvent(LoggingApplicationListener.java:225) at org.springframework.boot.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:201) at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:163) at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:136) at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:119) at org.springframework.boot.context.event.EventPublishingRunListener.publishEvent(EventPublishingRunListener.java:111) at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:65) at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54) at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:330) at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) at com.DemoApplication.main(DemoApplication.java:17) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) 2016-07-04 07:37:30.486 [restartedMain] INFO o.s.b.logging.ClasspathLoggingApplicationListener - Application failed to start with classpath: [file:/D:/workspace/demo/target/classes/, file:/D:/workspace/common/target/classes/] 2016-07-04 07:51:03.820 [restartedMain] INFO o.s.c.a.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1237898e: startup date [Mon Jul 04 07:51:03 CST 2016]; root of context hierarchy 2016-07-04 07:51:04.568 [restartedMain] INFO o.s.b.f.a.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring 2016-07-04 07:51:04.623 [restartedMain] INFO o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'configurationPropertiesRebinderAutoConfiguration' of type [class org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$67d72258] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2016-07-04 07:51:05.312 [restartedMain] INFO com.DemoApplication - No active profile set, falling back to default profiles: default
出現上面報錯時,頗有多是由於maxFileSize設置有不合理(通常是過小),文件rename太快,致使異常發生。
若是想了解詳解信息,能夠查看logback的日誌打印,能夠把logback的debug打開:(1)
<configuration debug="true">
(2)
<configuration>
<statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" />
... the rest of the configuration file
</configuration>
http://logback.qos.ch/manual/configuration.html
http://jira.qos.ch/browse/LOGBACK-1054
http://logback.qos.ch/dist/
https://codeload.github.com/qos-ch/logback/zip/v_1.1.5
logback-sizeAndTime.xml(按照以下配置,經測試是可用的。idea中可能出現問題,但重啓idea應用程序(是exit,不是close project)便可恢復正常)
<configuration> <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener"/> <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>mylog.txt</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- rollover daily --> <fileNamePattern>mylog-%d{yyyy-MM-dd}.%i.txt</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <!-- or whenever the file size reaches 100MB --> <maxFileSize>100MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <encoder> <pattern>%msg%n</pattern> </encoder> </appender> <root level="debug"> <appender-ref ref="ROLLING"/> </root> </configuration>
logback.xml
<configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <Pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread]%logger -%msg%n</Pattern> </encoder> </appender> <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>mylog.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- rollover daily --> <fileNamePattern>mylog-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <!-- or whenever the file size reaches 100MB --> <maxFileSize>10MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <encoder> <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread]%logger -%msg%n</pattern> </encoder> </appender> <root level="debug"> <appender-ref ref="ROLLING"/> <appender-ref ref="STDOUT"/> </root> </configuration>
By default, appenders are cumulative: a logger will log to the appenders attached to itself (if any) as well as all the appenders attached to its ancestors. Thus, attaching the same appender to multiple loggers will cause logging output to be duplicated.
Example: Duplicate appender (logback-examples/src/main/resources/chapters/configuration/duplicate.xml)
View as .groovy
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="chapters.configuration">
<appender-ref ref="STDOUT" />
</logger>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>
Running MyApp3
with duplicate.xml will yield the following output:
14:25:36.343 [main] INFO chapters.configuration.MyApp3 - Entering application. 14:25:36.343 [main] INFO chapters.configuration.MyApp3 - Entering application. 14:25:36.359 [main] DEBUG chapters.configuration.Foo - Did it again! 14:25:36.359 [main] DEBUG chapters.configuration.Foo - Did it again! 14:25:36.359 [main] INFO chapters.configuration.MyApp3 - Exiting application. 14:25:36.359 [main] INFO chapters.configuration.MyApp3 - Exiting application.
Notice the duplicated output. The appender named STDOUT is attached to two loggers, to root and tochapters.configuration. Since the root logger is the ancestor of all loggers and chapters.configuration is the parent of both chapters.configuration.MyApp3 and chapters.configuration.Foo, each logging request made with these two loggers will be output twice, once because STDOUT is attached to chapters.configuration and once because it is attached to root.
Appender additivity is not intended as a trap for new users. It is quite a convenient logback feature. For instance, you can configure logging such that log messages appear on the console (for all loggers in the system) while messages only from some specific set of loggers flow into a specific appender.
Example: Multiple appender (logback-examples/src/main/resources/chapters/configuration/restricted.xml)
View as .groovy
<configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>myApp.log</file>
<encoder>
<pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<logger name="chapters.configuration">
<appender-ref ref="FILE" />
</logger>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>
In this example, the console appender will log all the messages (for all loggers in the system) whereas only logging requests originating from the chapters.configuration logger and its children will go into the myApp.logfile.
http://logback.qos.ch/manual/configuration.html
or the shorter equivalent (DEPRECATED)
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>testFile.log</file>
...
<!-- layout are assigned the type ch.qos.logback.classic.PatternLayout by default -->
<layout>
<pattern>%msg%n</pattern>
</layout>
</appender>
to (GOOD)
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>testFile.log</file>
...
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%msg%n</pattern>
</encoder>
</appender>
or the shorter equivalent (GOOD)
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>testFile.log</file>
...
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
http://logback.qos.ch/codes.html
效果圖:
<?xml version="1.0" encoding="UTF-8"?> <!-- debug:打印logback內部日誌信息,實時查看logback的運行狀態,默認爲false --> <!-- scan:配置文件若是發生改變,是否被從新加載,默認爲true。 --> <!-- scanPeriod:設置檢測配置文件是否有修改的時間間隔,若是沒有給出時間單位,默認單位是毫秒,默認的時間間隔爲1分鐘,默認爲true。 --> <configuration debug="true" scan="true" scanPeriod="30 seconds"> <contextName>SpringBoot Demo</contextName> <!-- 時間戳定義,timeReference:使用日誌產生日期爲時間基準 --> <timestamp key="byDay" datePattern="yyyy-MM-dd" timeReference="contextBirth"/> <!--定義日誌文件的存儲地址 勿在 LogBack 的配置中使用相對路徑,可使用系統變量 --> <!-- <property name="LOG_HOME" value="${app.home}/log" /> --> <property name="LOG_HOME" value="log"/> <!-- appender很重要,一個配置文件會有多個appender --> <!-- ConsoleApperder意思是從console中打印出來 --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- On Windows machines setting withJansi to true enables ANSI color code interpretation by the Jansi library. This requires org.fusesource.jansi:jansi:1.8 on the class path. Note that Unix-based operating systems such as Linux and Mac OS X support ANSI color codes by default.
http://blog.csdn.net/u013613428/article/details/51499552
-->
<withJansi>true</withJansi> <!-- 過濾器,一個appender能夠有多個 --> <!-- 閾值過濾,就是log行爲級別過濾,debug及debug以上的信息會被打印出來 --> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>debug</level> </filter> <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> <!-- encoder編碼規則 --> <encoder> <!--<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>--> <!--<pattern>%d %contextName %msg%n</pattern>--> <!-- pattern模式 %d時間 %thread 線程名 %level行爲級別 %logger logger名稱 %method 方法名稱 %message 調用方法的入參消息 --> <pattern>%-4d [%green(%thread)] %highlight(%-5level) %cyan(%logger).%-10method - %message%n</pattern> </encoder>
<!-- 經常使用的Pattern變量,你們可打開該pattern進行輸出觀察 -->
<!--
<pattern>
%d{yyyy-MM-dd HH:mm:ss} [%level] - %msg%n
Logger: %logger
Class: %class
File: %file
Caller: %caller
Line: %line
Message: %m
Method: %M
Relative: %relative
Thread: %thread
Exception: %ex
xException: %xEx
nopException: %nopex
rException: %rEx
Marker: %marker
%n
</pattern>
-->
</appender> <!-- 按照天天生成日誌文件 --> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 日誌輸出文件 --> <file>${LOG_HOME}/LoggingBack.log</file> <!-- 追加日誌到原文件結尾 --> <append>true</append> <!-- timebasedrollingpolicy:演示時間和大小爲基礎的日誌文件歸檔 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- 歸檔的日誌文件的路徑,例現在天是2013-12-21日誌,當前寫的日誌文件路徑爲file節點指定。 --> <!--能夠將此文件與file指定文件路徑設置爲不一樣路徑,從而將當前日誌文件或歸檔日誌文件置不一樣的目錄。 --> <!--而2013-12-21的日誌文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 --> <!-- 文件滾動日期格式:天天:.YYYY-MM-dd(默認);每星期:.YYYY-ww;每個月:.YYYY-MM --> <!-- 每隔半天:.YYYY-MM-dd-a;每小時:.YYYY-MM-dd-HH;每分鐘:.YYYY-MM-dd-HH-mm --> <fileNamePattern>${LOG_HOME}/log-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <!-- 控制歸檔文件的最大數量的保存,刪除舊的文件,默認單位天數 --> <maxHistory>7</maxHistory> <!-- 設置當前日誌的文件的大小,決定日誌翻滾 --> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <!-- 除按日誌記錄以外,還配置了日誌文件不能超過10M(默認),若超過10M,日誌文件會以索引0開始, --> <maxFileSize>10MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy>
<!-- encoders 做用是將logger事件轉換成字節數組,並將字節數組寫入到輸出流-->
<encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n </pattern> </encoder> </appender> <appender name="FILE-INFO" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 這裏添加一個過濾器 --> <file>${LOG_HOME}/LoggingBack-info.log</file> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>INFO</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${LOG_HOME}/LOG-INFO-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <maxHistory>7</maxHistory> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>10MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n </pattern> </encoder> </appender> <appender name="FILE-ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 這裏添加一個過濾器 --> <file>${LOG_HOME}/LoggingBack-error.log</file> <!--<filter>標籤。 過濾器,執行一個過濾器會有返回個枚舉值,即DENY,NEUTRAL,ACCEPT其中之一。 返回DENY,日誌將當即被拋棄再也不通過其餘過濾器; 返回NEUTRAL,有序列表裏的下個過濾器過接着處理日誌; 返回ACCEPT,日誌會被當即處理,再也不通過剩餘過濾器。 過濾器被添加到<Appender> 中,爲<Appender> 添加一個或多個過濾器後,能夠用任意條件對日誌進行過濾。<Appender> 有多個過濾器時,按照配置順序執行。 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${LOG_HOME}/LOG-ERROR-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <maxHistory>7</maxHistory> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>10MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n </pattern> </encoder> </appender> <!-- 能夠寫多個日誌文件appender,而後區分多個模塊的日誌 --> <appender name="BACKUP" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${LOG_HOME}/LoggingBack2.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${LOG_HOME}/LOG-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <maxHistory>7</maxHistory> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>10MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n </pattern> </encoder> </appender> <!-- 爲單獨的包配置日誌級別,若root的級別大於此級別, 此處級別也會輸出 應用場景:生產環境通常不會將日誌級別設置爲trace或debug,可是爲詳細的記錄SQL語句的狀況, 可將hibernate的級別設置爲debug,如此一來,日誌文件中就會出現hibernate的debug級別日誌, 而其它包則會按root的級別輸出日誌 --> <logger name="org.hibernate.SQL" level="DEBUG"/> <logger name="org.hibernate.jdbc" level="DEBUG"/> <logger name="org.springframework" level="DEBUG"/> <!-- 指定一個包,name必填,additivity選填:控制是否繼承父類appender,默認true --> <!-- level選填,若是木有指定從最近的父類繼承,頂級爲root的級別 --> <logger name="com.wisely.ch7_7" additivity="true"> <appender-ref ref="FILE"/> <appender-ref ref="FILE-INFO"/> <appender-ref ref="FILE-ERROR"/> <appender-ref ref="BACKUP"/> </logger> <!-- root, 只有在level及以上級別的日誌會被輸出 --> <!-- 例如: 當root level設置爲INFO時, appender DEBUG中沒法獲取到DEBUG級別的日誌事件, 則DEBUG日誌信息也不會寫入debug.log中. --> <root level="DEBUG"> <appender-ref ref="STDOUT"/> </root> </configuration>
RollingFileAppender 繼承 FileAppender,可以滾動記錄文件。例如,RollingFileAppender能先記錄到文件"log.txt",而後當符合某個條件時,變成記錄到其餘文件。 RollingFileAppender 有兩個與之互動的重要子組件。第一個是RollingPolicy,負責滾動。第二個是 TriggeringPolicy,決定是否以及什麼時候進行滾動。因此,RollingPolicy 負責"什麼", TriggeringPolicy 負責"什麼時候"。
要想 RollingFileAppender 起做用,必須同時設置 RollingPolicy 和 TriggeringPolicy。不過,若是 RollingPolicy 也實現了 TriggeringPolicy 接口,那麼只須要設置 RollingPolicy。
FixedWindowRollingPolicy當發生滾動時,FixedWindowRollingPolicy 根據以下固定窗口(window)算法重命名文件。 選項"fileNamePattern"表明歸檔(滾動)記錄文件的文件名模式。該選項是必需的,且必需在模式的某處包含標誌"%i"。如示例3中的MyApp3-RollingFixedWindow.xml 。
TimeBasedRollingPolicy 或許是最受流行的滾動策略。它根據時間來制定滾動策略,例如根據日或月。TimeBasedRollingPolicy 既負責滾動也負責觸發滾動。實際上,TimeBasedRollingPolicy 同時實現了 RollingPolicy 接口和 TriggeringPolicy 接口。和 FixedWindowRollingPolicy同樣,TimeBasedRollingPolicy 也支持自動壓縮文件。若是"fileNamePattern"選項以".gz"或".zip"結尾,就表示須要壓縮。如示例3中的MyApp3-RollingTimeBased.xml 。
SizeAndTimeBasedFNATP按照日期進行歸檔的同時限制每一個記錄文件的大小,特別是當後處理工具對記錄文件大小有限制時。Logback 爲此提供了 SizeAndTimeBasedFNATP,它是TimeBasedRollingPolicy 的子組件,FNATP 表明"FNATP stands for File Naming And Triggering Policy"。 下面的例子MyApp3-sizeAndTime.xml演示了基於大小和時間的記錄文件歸檔。
如給定的一個格式:%-5p [%t]: %m%n中,並無明確的分隔轉換字符和普通文本的字符存在。PatternLayout能本身區分普通文本和轉換字符。其中%-5p是日誌的調用級別。事件是左對齊的,5個字符寬度。
格式修飾符,放在%和轉換符之間。 第一個可選的格式修飾符是左對齊(-);第二個可選的格式修飾符是字段最小寬度。一個整數。表示輸出的最小字符數。若是數據未達到指定最小大小,那麼它將以左填充(默認)或者右填充方式(左對齊狀況下只能使用右填充了)。用空格填充,直到達到最小寬度。若是大於指定最小寬度,不會被截斷 。固然能夠指定最大字符數,使用.符號加數字表示最大字符數。若是大於指定長度,多餘的字符會被刪除。它是從前面刪除,而不是從後面刪除的。如最大字符是8個,數據有10個字符,那麼前面兩個字符會被刪除。
%20.30c 右對齊,最少20字符,最多30字符,填充或截取規則略
%-20.30c 左對齊,最少20字符,最多30字符,填充或截取規則略
Appender累積
默認狀況下,appender 是可累積的:logger 會把記錄輸出到它自身的 appender 和它全部祖先的 appender。所以,把同一 appender 關聯到多個 logger 會致使重複輸出,以下面的配置文件會致使重複的輸出:
<configuration>
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>
%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="chapters.configuration">
<appender-ref ref="STDOUT" />
</logger>
<root level="debug">
<appender-ref ref="STDOUT" /> <!—這會致使重複輸出-->
</root>
</configuration>
輸出結果以下:
20:53:29.328 [main] INFO c.t.chapters.configuration.MyApp2 - Entering application.
20:53:29.328 [main] INFO c.t.chapters.configuration.MyApp2 - Entering application.
20:53:29.328 [main] DEBUG com.ttpod.chapters.configuration.Foo - Did it again!
20:53:29.328 [main] DEBUG com.ttpod.chapters.configuration.Foo - Did it again!
20:53:29.328 [main] INFO c.t.chapters.configuration.MyApp2 - Exiting application.
20:53:29.328 [main] INFO c.t.chapters.configuration.MyApp2 - Exiting application.
覆蓋默認的累積行爲
若是你以爲默認的累積行爲不合適,能夠設置疊加性標識爲 false 以關閉它。 這樣的話,logger 樹裏的某個分支能夠輸出到與其餘 logger 不一樣的 appender。
示例:疊加性標識
<configuration>
…………
<logger name="com.ttpod.chapters.configuration.Foo" additivity="false">
<appender-ref ref="FILE" />
</logger>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>
輸出結果:
Entering application.
Exiting application.
此例中,logger"chapters.configuration.Foo"關聯 appender"FILE",它的疊加性標記爲false,這樣它的記錄輸出僅會被髮送到 appender"FILE",不會被髮送到更高logger 等級關聯的 appender。其餘 logger 不受此影響。 用 additivityFlag.xml 配置 MyApp3 , 運 行 後 , 控 制 臺 上 由 輸 出由"chapters.configuration.MyApp3"產生的記錄。而 logger" chapters.configuration.Foo"將且僅僅將輸出到文件 foo.log。
http://www.cnblogs.com/luowei010101/archive/2012/01/04/2312438.html
When you specify the MaxFileSize to be used by the SizeBasedRollingPolicy, logback expects a rather precise format:
Here are some correct values: 500KB, 15MB, 2GB.
TriggeringPolicy
was set for the RollingFileAppender
.The RollingFileAppender
must be set up with a TriggeringPolicy
. It permits the Appender to know when the rollover must be activated.
To find more information about TriggeringPolicy
objects, please read the following javadocs:
Please note that the TimeBasedRollingPolicy
is a TriggeringPolicy and and RollingPolicy
at the same time.
The %i conversion token is mandatory for size and time based archiving. In case the %i token is missing,SizeAndTimeBasedFNATP
attached to RollingFileAppender
will detect the omission and will not start.
http://logback.qos.ch/codes.html
SizeBasedTriggeringPolicy
looks at the size of the currently active file. If it grows larger than the specified size, it will signal the owning RollingFileAppender
to trigger the rollover of the existing active file.
SizeBasedTriggeringPolicy
accepts only one parameter, namely maxFileSize, with a default value of 10 MB.
The maxFileSize option can be specified in bytes, kilobytes, megabytes or gigabytes by suffixing a numeric value with KB, MB and respectively GB. For example, 5000000, 5000KB, 5MB and 2GB are all valid values, with the first three being equivalent.
Here is a sample configuration with a RollingFileAppender
in conjunction with SizeBasedTriggeringPolicy
triggering rollover when the log file reaches 5MB in size.
Example: Sample configuration of a RollingFileAppender
using a SizeBasedTriggeringPolicy
(logback-examples/src/main/resources/chapters/appenders/conf/logback-RollingSizeBased.xml)
<configuration> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>test.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <fileNamePattern>test.%i.log.zip</fileNamePattern> <minIndex>1</minIndex> <maxIndex>3</maxIndex> </rollingPolicy> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <maxFileSize>5MB</maxFileSize> </triggeringPolicy> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration>
file:///D:/jar/logback-1.1.7/docs/manual/appenders.html#TimeBasedRollingPolicy
The default log configuration will echo messages to the console as they are written. By default ERROR
, WARN
and INFO
level messages are logged. You can also enable a 「debug」 mode by starting your application with a --debug
flag.
$ java -jar myapp.jar --debug
you can also specify |
When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate and Spring) are configured to output more information. Enabling the debug mode does not configure your application log all messages with DEBUG
level.
If your terminal supports ANSI, color output will be used to aid readability. You can set spring.output.ansi.enabled
to a supported value to override the auto detection.
Color coding is configured using the %clr
conversion word. In its simplest form the converter will color the output according to the log level, for example:
%clr(%5p)
The mapping of log level to a color is as follows:
Level | Color |
---|---|
|
Red |
|
Red |
|
Yellow |
|
Green |
|
Green |
|
Green |
Alternatively, you can specify the color or style that should be used by providing it as an option to the conversion. For example, to make the text yellow:
%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow}
The following colors and styles are supported:
blue
cyan
faint
green
magenta
red
yellow
The various logging systems can be activated by including the appropriate libraries on the classpath, and further customized by providing a suitable configuration file in the root of the classpath, or in a location specified by the Spring Environment
property logging.config
.
Since logging is initialized before the |
Depending on your logging system, the following files will be loaded:
Logging System | Customization |
---|---|
Logback |
|
Log4j |
|
Log4j2 |
|
JDK (Java Util Logging) |
|
When possible we recommend that you use the |
There are known classloading issues with Java Util Logging that cause problems when running from an ‘executable jar’. We recommend that you avoid it if at all possible. |
To help with the customization some other properties are transferred from the Spring Environment
to System properties:
Spring Environment | System Property | Comments |
---|---|---|
|
|
The conversion word that’s used when logging exceptions. |
|
|
Used in default log configuration if defined. |
|
|
Used in default log configuration if defined. |
|
|
The log pattern to use on the console (stdout). (Not supported with JDK logger.) |
|
|
The log pattern to use in a file (if LOG_FILE enabled). (Not supported with JDK logger.) |
|
|
The format to use to render the log level (default |
|
|
The current process ID (discovered if possible and when not already defined as an OS environment variable). |
All the logging systems supported can consult System properties when parsing their configuration files. See the default configurations in spring-boot.jar
for examples.
If you want to use a placeholder in a logging property, you should use Spring Boot’s syntax and not the syntax of the underlying framework. Notably, if you’re using Logback, you should use
|
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html
默認狀況下,Spring Boot的日誌是輸出到控制檯的,不寫入任何日誌文件。
要讓Spring Boot輸出日誌文件,最簡單的方式是在application.properties配置文件中配置logging.path鍵值,以下:(日誌文件爲spring.log)
logging.path=/var/log
第二種方法是在application.properties配置文件中配置logging.file鍵值,以下:
logging.file=/var/log/myapp.log
這兩種配置方法適用於開發階段,對於部署則存在必定的問題。好比部署到不一樣的環境,可能就存在須要修改application.properties文件的狀況,這就意味着須要從新打包,再次部署,顯得不便捷。
有鑑於此,Spring Boot提供了一種覆寫application.properties配置文件中鍵值的方法,在命令行經過指定參數來實現覆寫——在運行時把命令行參數看成標準的系統屬性,以下:
java -jar -Dlogging.path=/tmp myapp.jar
最後,還能夠在命令行調用Spring Boot的Maven插件時覆寫這個值。可是,直接使用系統屬性對於插件方式是無效的。須要使用run.jvmArguments參數來指定系統屬性,設置想要的值:
mvn spring-boot:run -Drun.jvmArguments="-Dlogging.path=/tmp"
一切都變得很完美了!
http://m.blog.csdn.net/article/details?id=50737925
<appender>:
<appender>是<configuration>的子節點,是負責寫日誌的組件。
<appender>有兩個必要屬性name和class。name指定appender名稱,class指定appender的全限定名。
1.ConsoleAppender:
把日誌添加到控制檯,有如下子節點:
<encoder>:對日誌進行格式化。(具體參數稍後講解 )
<target>:字符串 System.out 或者 System.err ,默認 System.out ;
rollingPolicy:
TimeBasedRollingPolicy: 最經常使用的滾動策略,它根據時間來制定滾動策略,既負責滾動也負責出發滾動。有如下子節點:
<fileNamePattern>:
必要節點,包含文件名及「%d」轉換符, 「%d」能夠包含一個java.text.SimpleDateFormat指定的時間格式,如:%d{yyyy-MM}。若是直接使用 %d,默認格式是 yyyy-MM-dd。
RollingFileAppender 的file字節點無關緊要,經過設置file,能夠爲活動文件和歸檔文件指定不一樣位置,當前日誌老是記錄到file指定的文件(活動文件),活動文件的名字不會改變;若是沒設置file,活動文件的名字會根據fileNamePattern 的值,每隔一段時間改變一次。「/」或者「\」會被當作目錄分隔符。
http://blog.csdn.net/haidage/article/details/6794529 good
logback-spring.xml
Logback的核心對象:Logger、Appender、Layout
Logback主要創建於Logger、Appender 和 Layout 這三個類之上。
Logger:日誌的記錄器,把它關聯到應用的對應的context上後,主要用於存放日誌對象,也能夠定義日誌類型、級別。Logger對象通常多定義爲靜態常量
Appender:用於指定日誌輸出的目的地,目的地能夠是控制檯、文件、遠程套接字服務器、 MySQL、 PostreSQL、Oracle和其餘數據庫、 JMS和遠程UNIX Syslog守護進程等。
Layout:負責把事件轉換成字符串,格式化的日誌信息的輸出。具體的Layout通配符,能夠直接查看幫助文檔。
三、Level 有效級別
Logger能夠被分配級別。級別包括:TRACE、DEBUG、INFO、WARN和ERROR,定義於ch.qos.logback.classic.Level類。程序會打印高於或等於所設置級別的日誌,設置的日誌等級越高,打印出來的日誌就越少。若是設置級別爲INFO,則優先級高於等於INFO級別(如:INFO、 WARN、ERROR)的日誌信息將能夠被輸出,小於該級別的如DEBUG將不會被輸出。爲確保全部logger都可以最終繼承一個級別,根logger老是有級別,默認狀況下,這個級別是DEBUG
四、 三值邏輯
Logback的過濾器基於三值邏輯(ternary logic),容許把它們組裝或成鏈,從而組成任意的複合過濾策略。過濾器很大程度上受到Linux的iptables啓發。這裏的所謂三值邏輯是說,過濾器的返回值只能是ACCEPT、DENY和NEUTRAL的其中一個。
若是返回DENY,那麼記錄事件當即被拋棄,再也不通過剩餘過濾器;
若是返回NEUTRAL,那麼有序列表裏的下一個過濾器會接着處理記錄事件;
若是返回ACCEPT,那麼記錄事件被當即處理,再也不通過剩餘過濾器。
五、Filter 過濾器
Logback-classic提供兩種類型的過濾器:常規過濾器和TuroboFilter過濾器。Logback總體流程:Logger 產生日誌信息;Layout修飾這條msg的顯示格式;Filter過濾顯示的內容;Appender具體的顯示,即保存這日誌信息的地方。
Java項目中通常都會應用好比struts、spring、hibernate等開源框架,而這些框架不少是應用log4j記錄日誌的,因此咱們考慮用log4j + slf4j + logback 。這樣咱們須要導入log4j-over-slf4j-1.6.4.jar 、logback-classic-1.0.1.jar 、logback-core-1.0.1.jar 、slf4j-api-1.6.4.jar ,若是你要用到EvaluatorFilter過濾器來過濾日誌Msg中的特殊字符須要導入其依賴包 janino-2.3.2.jar
http://www.cnblogs.com/yongze103/archive/2012/05/05/2484753.html
Coloring
Grouping by parentheses as explained above allows coloring of sub-patterns. As of version 1.0.5, PatternLayout recognizes "%black", "%red", "%green","%yellow","%blue", "%magenta","%cyan", "%white", "%gray", "%boldRed","%boldGreen", "%boldYellow", "%boldBlue", "%boldMagenta""%boldCyan", "%boldWhite" and "%highlight" as conversion words. These conversion words are intended to contain a sub-pattern. Any sub-pattern enclosed by a coloring word will be output in the specified color.
Below is a configuration file illustrating coloring. Note the %cyan conversion specifier enclosing "%logger{15}". This will output the logger name abbreviated to 15 characters in cyan. The %highlight conversion specifier prints its sub-pattern in bold-red for events of level ERROR, in red for WARN, in BLUE for INFO, and in the default color for other levels.
Example: Highlighting levels (logback-examples/src/main/resources/chapters/layouts/highlighted.xml) View as .groovy
<configuration debug="true">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- On Windows machines setting withJansi to true enables ANSI
color code interpretation by the Jansi library. This requires
org.fusesource.jansi:jansi:1.8 on the class path. Note that
Unix-based operating systems such as Linux and Mac OS X
support ANSI color codes by default. -->
<withJansi>true</withJansi>
<encoder>
<pattern>[%thread] %highlight(%-5level) %cyan(%logger{15}) - %msg %n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration>
Here is the corresponding output:
It takes very few lines of code to create a coloring conversion word. The section entitled creating a custom conversion specifier discusses the steps necessary for registering a conversion word in your configuration file.
http://logback.qos.ch/manual/layouts.html
<configuration> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>test.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <fileNamePattern>test.%i.log.zip</fileNamePattern> <minIndex>1</minIndex> <maxIndex>3</maxIndex> </rollingPolicy> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <maxFileSize>5MB</maxFileSize> </triggeringPolicy> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration>
http://blog.csdn.net/huozhonbin/article/details/12560617
下載對於的JAR 包:
http://logback.qos.ch/
logback-access-1.1.2.jar
logback-classic-1.1.2.jar
logback-core-1.1.2.jar
http://www.slf4j.org/
slf4j-api-1.7.10.jar
mvaven , 配置以下:
<dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.3</version> </dependency><dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-access</artifactId> <version>1.1.3</version> </dependency><dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.1.3</version> </dependency><dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.12</version> </dependency>
將logback.xml 放置到web工程的classes目路下,運行項目
http://www.cnblogs.com/dragonflyyi/p/4245250.html
http://blog.csdn.net/wangdongsong1229/article/details/17463113
Code:
package com.wisely.ch7_7; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @SpringBootApplication public class Ch77Application { private static final Logger LOGGER = LoggerFactory.getLogger(Ch77Application.class); @RequestMapping(value = "/search", produces = {MediaType.APPLICATION_JSON_VALUE}) public Person search(String personName) { LOGGER.info("info level"); LOGGER.error("error level"); LOGGER.warn("warn level"); LOGGER.debug("debug level"); LOGGER.info("info level"); return new Person(personName, 32, "shanghai"); } public static void main(String[] args) { SpringApplication.run(Ch77Application.class, args); } }
package com.wisely.ch7_7; public class Person { private String name; private Integer age; private String address; public Person() { super(); } public Person(String name, Integer age, String address) { super(); this.name = name; this.age = age; this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.wisely</groupId> <artifactId>ch7_7</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>ch7_7</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.0.M1</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> <pluginRepository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> </pluginRepositories> </project>
1、logback的介紹
Logback是由log4j創始人設計的又一個開源日誌組件。logback當前分紅三個模塊:logback-core,logback- classic和logback-access。logback-core是其它兩個模塊的基礎模塊。logback-classic是log4j的一個 改良版本。此外logback-classic完整實現SLF4J API使你能夠很方便地更換成其它日誌系統如log4j或JDK14 Logging。logback-access訪問模塊與Servlet容器集成提供經過Http來訪問日誌的功能。 Logback是要與SLF4J結合起來用兩個組件的官方網站以下:
logback的官方網站: http://logback.qos.ch
SLF4J的官方網站:http://www.slf4j.org
本文章用到的組件以下:請自行到官方網站下載!
logback-access-1.0.0.jar
logback-classic-1.0.0.jar
logback-core-1.0.0.jar
slf4j-api-1.6.0.jar
maven配置
<dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.0.11</version> </dependency>
這樣依賴包所有自動下載了!
2、logback取代 log4j的理由:
Logback和log4j是很是類似的,若是你對log4j很熟悉,那對logback很快就會駕輕就熟。下面列了logback相對於log4j的一些優勢:
一、更快的實現 Logback的內核重寫了,在一些關鍵執行路徑上性能提高10倍以上。並且logback不只性能提高了,初始化內存加載也更小了。
二、很是充分的測試 Logback通過了幾年,數不清小時的測試。Logback的測試徹底不一樣級別的。在做者的觀點,這是簡單重要的緣由選擇logback而不是log4j。
三、Logback-classic很是天然實現了SLF4j Logback-classic實現了 SLF4j。在使用SLF4j中,你都感受不到logback-classic。並且由於logback-classic很是天然地實現了SLF4J, 所 以切換到log4j或者其餘,很是容易,只須要提供成另外一個jar包就OK,根本不須要去動那些經過SLF4JAPI實現的代碼。
四、很是充分的文檔 官方網站有兩百多頁的文檔。
五、自動從新加載配置文件 當配置文件修改了,Logback-classic能自動從新加載配置文件。掃描過程快且安全,它並不須要另外建立一個掃描線程。這個技術充分保證了應用程序能跑得很歡在JEE環境裏面。
六、Lilith Lilith是log事件的觀察者,和log4j的chainsaw相似。而lilith還能處理大數量的log數據 。
七、謹慎的模式和很是友好的恢復 在謹慎模式下,多個FileAppender實例跑在多個JVM下,能 夠安全地寫道同一個日誌文件。RollingFileAppender會有些限制。Logback的FileAppender和它的子類包括 RollingFileAppender可以很是友好地從I/O異常中恢復。
八、配置文件能夠處理不一樣的狀況 開發人員常常須要判斷不一樣的Logback配置文件在不一樣的環境下(開發,測試,生產)。而這些配置文件僅僅只有一些很小的不一樣,能夠經過,和來實現,這樣一個配置文件就能夠適應多個環境。
九、Filters(過濾器) 有些時候,須要診斷一個問題,須要打出日誌。在log4j,只有下降日誌級別,不過這樣會打出大量的日誌,會影響應用性能。在Logback,你能夠繼續 保持那個日誌級別而除掉某種特殊狀況,如alice這個用戶登陸,她的日誌將打在DEBUG級別而其餘用戶能夠繼續打在WARN級別。要實現這個功能只需 加4行XML配置。能夠參考MDCFIlter 。
十、SiftingAppender(一個很是多功能的Appender) 它能夠用來分割日誌文件根據任何一個給定的運行參數。如,SiftingAppender可以區別日誌事件跟進用戶的Session,而後每一個用戶會有一個日誌文件。
十一、自動壓縮已經打出來的log RollingFileAppender在產生新文件的時候,會自動壓縮已經打出來的日誌文件。壓縮是個異步過程,因此甚至對於大的日誌文件,在壓縮過程當中應用不會受任何影響。
十二、堆棧樹帶有包版本 Logback在打出堆棧樹日誌時,會帶上包的數據。
1三、自動去除舊的日誌文件 經過設置TimeBasedRollingPolicy或者SizeAndTimeBasedFNATP的maxHistory屬性,你能夠控制已經產生日誌文件的最大數量。若是設置maxHistory 12,那那些log文件超過12個月的都會被自動移除。
總之,logback比log4j太優秀了,讓咱們的應用所有創建logback上吧 !
三、Logback的配置介紹
一、Logger、appender及layout
Logger做爲日誌的記錄器,把它關聯到應用的對應的context上後,主要用於存放日誌對象,也能夠定義日誌類型、級別。
Appender主要用於指定日誌輸出的目的地,目的地能夠是控制檯、文件、遠程套接字服務器、 MySQL、 PostreSQL、 Oracle和其餘數據庫、 JMS和遠程UNIX Syslog守護進程等。
Layout 負責把事件轉換成字符串,格式化的日誌信息的輸出。
二、logger context
各個logger 都被關聯到一個 LoggerContext,LoggerContext負責製造logger,也負責以樹結構排列各 logger。其餘全部logger也經過org.slf4j.LoggerFactory 類的靜態方法getLogger取得。 getLogger方法以 logger 名稱爲參數。用同一名字調用LoggerFactory.getLogger 方法所獲得的永遠都是同一個logger對象的引用。
三、有效級別及級別的繼承
Logger 能夠被分配級別。級別包括:TRACE、DEBUG、INFO、WARN 和 ERROR,定義於 ch.qos.logback.classic.Level類。若是 logger沒有被分配級別,那麼它將從有被分配級別的最近的祖先那裏繼承級別。root logger 默認級別是 DEBUG。
四、打印方法與基本的選擇規則
打印方法決定記錄請求的級別。例如,若是 L 是一個 logger 實例,那麼,語句 L.info("..")是一條級別爲 INFO 的記錄語句。記錄請求的級別在高於或等於其 logger 的有效級別時被稱爲被啓用,不然,稱爲被禁用。記錄請求級別爲 p,其 logger的有效級別爲 q,只有則當 p>=q時,該請求才會被執行。
該規則是 logback 的核心。級別排序爲: TRACE < DEBUG < INFO < WARN < ERROR。
http://www.cnblogs.com/yuanermen/archive/2012/02/13/2348942.html
LogBack是一個日誌框架,它是Log4j做者Ceki的又一個日誌組件。
slf4j是The Simple Logging Facade for Java的簡稱,是一個簡單日誌門面抽象框架,它自己只提供了日誌Facade API和一個簡單的日誌類實現,通常常配合Log4j,LogBack,java.util.logging使用。Slf4j做爲應用層的Log接入時,程序能夠根據實際應用場景動態調整底層的日誌實現框架(Log4j/LogBack/JdkLog...);
LogBack和Log4j都是開源日記工具庫,LogBack是Log4j的改良版本,比Log4j擁有更多的特性,同時也帶來很大性能提高。
LogBack官方建議配合Slf4j使用,這樣能夠靈活地替換底層日誌框架。
LogBack分爲3個組件,logback-core, logback-classic 和 logback-access。
其中logback-core提供了LogBack的核心功能,是另外兩個組件的基礎。
logback-classic則實現了Slf4j的API,因此當想配合Slf4j使用時,則須要引入這個包。
logback-access是爲了集成Servlet環境而準備的,可提供HTTP-access的日誌接口。
OFF、
FATAL、
ERROR、
WARN、
INFO、
DEBUG、
ALL
從下向上,當選擇了其中一個級別,則該級別向下的行爲是不會被打印出來。
舉個例子,當選擇了INFO級別,則INFO如下的行爲則不會被打印出來。
咱們從java代碼最簡單的獲取logger開始
Logger logger = LoggerFactory.getLogger(xxx.class.getName());
LoggerFactory是slf4j的日誌工廠,獲取logger方法就來自這裏。
public static Logger getLogger(String name) { ILoggerFactory iLoggerFactory = getILoggerFactory(); return iLoggerFactory.getLogger(name); }
這個方法裏面有分爲兩個過程。
第一個過程是獲取ILoggerFactory,就是真正的日誌工廠。
第二個過程就是從真正的日誌工廠中獲取logger。
第一個過程又分爲三個部分。
第一個部分加載org/slf4j/impl/StaticLoggerBinder.class文件
paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH);//STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class"
第二部分隨機選取一個StaticLoggerBinder.class來建立一個單例
當項目中存在多個StaticLoggerBinder.class文件時,運行項目會出現如下日誌:
SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/C:/Users/zhangheng5/.m2/repository/ch/qos/logback/logback-classic/1.1.3/logback-classic-1.1.3.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:/C:/Users/zhangheng5/.m2/repository/org/slf4j/slf4j-log4j12/1.7.12/slf4j-log4j12-1.7.12.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
最後會隨機選擇一個StaticLoggerBinder.class來建立一個單例
StaticLoggerBinder.getSingleton()
第三部分返回一個ILoggerFactory實例
StaticLoggerBinder.getSingleton().getLoggerFactory();
因此slf4j與其餘實際的日誌框架的集成jar包中,都會含有這樣的一個org/slf4j/impl/StaticLoggerBinder.class類文件,而且提供一個ILoggerFactory的實現。
第二個過程就是每個和slf4j集成的日誌框架中實現ILoggerFactory方法getLogger()的實例所作的事了。
slf4j-api
logback-core
logback-classic(含有對slf4j的集成包)
<!-- slf4j-api --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.12</version> </dependency> <!-- logback --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.3</version> </dependency>
<?xml version="1.0" encoding="UTF-8"?> <configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root> </configuration>
文件位置位於src/main/resources下,名字默認爲logback.xml。
固然,logback也支持groovy格式的配置文件,若是你會用那更好。
接下來,本身隨便寫一個類調用一下logger
package log.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author jiangmitiao * @date 2016/3/24 * @description TODO */ public class Foo { public static void doIt(){ Logger logger = LoggerFactory.getLogger(Foo.class.getName()); logger.debug("let`s do it"); } } package log.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyApp1 { public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(MyApp1.class.getName()); logger.info("before"); Foo.doIt(); logger.info("after"); try { int i = 10 / 0; } catch (Exception e) { logger.error("errorTest",e); } } }
最後的結果是:
16:22:13.459 [main] INFO log.test.MyApp1 - before 16:22:13.463 [main] DEBUG log.test.Foo - let`s do it 16:22:13.463 [main] INFO log.test.MyApp1 - after 16:22:13.466 [main] ERROR log.test.MyApp1 - errorTest java.lang.ArithmeticException: / by zero at log.test.MyApp1.main(MyApp1.java:19) ~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_25] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.6.0_25] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_25] at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_25] at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) [idea_rt.jar:na]
配置規則簡述
上邊這麼簡單的配置固然是沒有用的,下面這個就可以說明logback配置文件的編寫規則了。
<!-- scan的意思是是否掃描 seconds是說多長時間掃描一次 --> <configuration scan="true" scanPeriod="30 seconds" debug="false" packagingData="true"> <!-- 項目名稱 --> <contextName>myApp1 contextName</contextName> <!-- 屬性 --> <property name="USER_HOME" value="./log"/> <!-- 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" timeReference="contextBirth"/> <!-- appender很重要,一個配置文件會有多個appender --> <!-- ConsoleApperder意思是從console中打印出來 --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- 過濾器,一個appender能夠有多個 --> <!-- 閾值過濾,就是log行爲級別過濾,debug及debug以上的信息會被打印出來 --> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>debug</level> </filter> <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> <!-- encoder編碼規則 --> <encoder> <!--<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>--> <!--<pattern>%d %contextName %msg%n</pattern>--> <!-- pattern模式 %d時間 %thread 線程名 %level行爲級別 %logger logger名稱 %method 方法名稱 %message 調用方法的入參消息 --> <pattern>%-4d [%thread] %highlight%-5level %cyan%logger.%-10method - %message%n</pattern> </encoder> </appender> <!-- FileAppender 輸出到文件 --> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <!-- 文件存放位置 %{xxx} 就是以前定義的屬性xxx --> <file>${USER_HOME}/myApp1log-${bySecond}.log</file> <encoder> <!-- %date和%d是一個意思 %file是所在文件 %line是所在行 --> <pattern>%date %level [%thread] %logger{30} [%file:%line] %msg%n</pattern> </encoder> </appender> <!-- 輸出到HTML格式的文件 --> <appender name="HTMLFILE" class="ch.qos.logback.core.FileAppender"> <!-- 過濾器,這個過濾器是行爲過濾器,直接過濾掉了除debug外全部的行爲信息 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>debug</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder"> <!-- HTML輸出格式 能夠和上邊差很少 --> <layout class="ch.qos.logback.classic.html.HTMLLayout"> <pattern>%relative%thread%mdc%level%logger%msg</pattern> </layout> </encoder> <file>${USER_HOME}/test.html</file> </appender> <!-- 滾動日誌文件,這個比較經常使用 --> <appender name="ROLLINGFILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 當project等於true的時候file就不會起效果--> <prudent>true</prudent> <!--<file>${USER_HOME}/logFile.log</file>--> <!-- 按天新建log日誌 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover --> <fileNamePattern>${USER_HOME}/logFile.%d{yyyy-MM-dd}_%i.log</fileNamePattern> <!-- 保留30天的歷史日誌 --> <maxHistory>30</maxHistory> <!-- 基於大小和時間,這個能夠有,能夠沒有 --> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <!-- or whenever the file size reaches 100MB --> <!-- 當一個日誌大小大於10KB,則換一個新的日誌。日誌名的%i從0開始,自動遞增 --> <maxFileSize>10KB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <encoder> <!-- %ex就是指拋出的異常,full是顯示所有,若是在{}中寫入數字,則表示展現多少行 --> <pattern>%-4date [%thread] %-5level %logger{35} - %msg%n%ex{full, DISPLAY_EX_EVAL}</pattern> </encoder> </appender> <!-- 重點來了,上邊都是appender輸出源。這裏開始就是looger了 --> <!-- name意思是這個logger管的哪一片,像下面這個管的就是log/test包下的全部文件 level是隻展現什麼行爲信息級別以上的,相似閾值過濾器 additivity表示是否再拋出事件,就是說若是有一個logger的name是log,若是這個屬性是true,另外一個logger就會在這個logger處理完後接着繼續處理 --> <logger name="log.test" level="INFO" additivity="false"> <!-- 鏈接輸出源,也就是上邊那幾個輸出源,你能夠隨便選幾個appender --> <appender-ref ref="STDOUT"/> <appender-ref ref="ROLLINGFILE"/> <appender-ref ref="HTMLFILE"/> </logger> <!-- 這個logger詳細到了類 --> <logger name="log.test.Foo" level="debug" additivity="false"> <appender-ref ref="STDOUT"/> <appender-ref ref="ROLLINGFILE"/> <appender-ref ref="HTMLFILE"/> </logger> <!-- Strictly speaking, the level attribute is not necessary since --> <!-- the level of the root level is set to DEBUG by default. --> <!-- 這就是上邊logger沒有管到的狀況下 root默認接管全部logger --> <root level="debug"> <appender-ref ref="STDOUT"/> </root> </configuration>
Logback的過濾器基於三值邏輯(ternary logic),容許把它們組裝或成鏈,從而組成任意的複合過濾策略。過濾器很大程度上受到Linux的iptables啓發。這裏的所謂三值邏輯是說,過濾器的返回值只能是ACCEPT、DENY和NEUTRAL的其中一個。
若是返回DENY,那麼記錄事件當即被拋棄,再也不通過剩餘過濾器;
若是返回NEUTRAL,那麼有序列表裏的下一個過濾器會接着處理記錄事件;
若是返回ACCEPT,那麼記錄事件被當即處理,再也不通過剩餘過濾器。
寫一個簡單的過濾器你們就明白了。
package log.test; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.filter.Filter; import ch.qos.logback.core.spi.FilterReply; public class SampleFilter extends Filter<ILoggingEvent> { @Override public FilterReply decide(ILoggingEvent event) { if (event.getMessage().contains("let")) { return FilterReply.ACCEPT; } else { return FilterReply.DENY; } } }
能夠選擇任意幾個輸出源加入這個filter
<filter class="log.test.SampleFilter" />
最後的結果是,加入該filter的輸出源只能輸出Foo.doIt()中的日誌了。
logback配置比較簡單,官網手冊也是比較容易看懂的。除上邊幾種輸出源以外,logback還支持輸出到遠程套接字服務器、 MySQL、 PostreSQL、Oracle和其餘數據庫、 JMS和遠程UNIX Syslog守護進程等等。
第一次學習log方面的知識,若有錯誤,請不吝賜教。
http://logback.qos.ch/manual/index.html
http://www.cnblogs.com/mailingfeng/p/3499436.html
http://yuri-liuyu.iteye.com/blog/954038
http://www.cnblogs.com/yongze103/archive/2012/05/05/2484753.html
http://blog.csdn.net/haidage/article/details/6794509
http://my.oschina.net/jiangmitiao/blog/647902
SLF4J——Simple Logging Facade For Java,它是一個針對於各種Java日誌框架的統一Facade抽象。Java日誌框架衆多——經常使用的有java.util.logging
, log4j
, logback
,commons-logging
, Spring框架使用的是Jakarta Commons Logging API (JCL)。而SLF4J定義了統一的日誌抽象接口,而真正的日誌實現則是在運行時決定的——它提供了各種日誌框架的binding。
Logback是log4j框架的做者開發的新一代日誌框架,它效率更高、可以適應諸多的運行環境,同時自然支持SLF4J。
Spring Boot實現了一套日誌系統——它可以根據類路徑上的內容來決定使用哪種日誌框架,logback
是最優先的選擇。配置了logback.xml
能夠利用Spring Boot提供的默認日誌配置:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <include resource="org/springframework/boot/logging/logback/base.xml"/> <logger name="org.springframework.web" level="DEBUG"/> </configuration>
這樣就定義了一個<logger>
捕獲org.springframework.web
的日誌,日誌級別是DEBUG
,base.xml
內容以下:
<included> <include resource="org/springframework/boot/logging/logback/defaults.xml" /> <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}"/> <include resource="org/springframework/boot/logging/logback/console-appender.xml" /> <include resource="org/springframework/boot/logging/logback/file-appender.xml" /> <root level="INFO"> <appender-ref ref="CONSOLE" /> <appender-ref ref="FILE" /> </root> </included>
Spring Boot的日誌系統預先定義了一些系統變量:
${PID}
,當前進程ID${LOG_FILE}
,Spring Boot配置文件中logging.file
的值${LOG_PATH}
, Spring Boot配置文件中logging.path
的值同時默認狀況下包含另個appender
——一個是控制檯,一個是文件,分別定義在console-appender.xml
和file-appender.xml
中。同時對於應用的日誌級別也能夠經過application.properties
進行定義:
logging.level.org.springframework.web=DEBUG logging.level.org.hibernate=ERROR
這等價於在logback.xml
配置appender
的日誌級別。
Logback使用appender
來定義日誌輸出,在開發過程當中最經常使用的是將日誌輸出到控制檯:
<appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <Pattern>.%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg %n</Pattern> </encoder> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>TRACE</level> </filter> </appender>
<encoder>
表示對日誌進行編碼:
%d{HH:mm:ss.SSS}
——日誌輸出時間%thread
——輸出日誌的進程名字,這在Web應用以及異步任務處理中頗有用%-5level
——日誌級別,而且使用5個字符靠左對齊%logger{36}
——日誌輸出者的名字%msg
——日誌消息%n
——平臺的換行符在這種格式下一條日誌的輸出結果以下:
0:12:51.012 [qtp231719230-45] DEBUG o.c.d.r.util.LoggingResponseFilter
另外一種常見的日誌輸出到文件,隨着應用的運行時間愈來愈長,日誌也會增加的愈來愈多,將他們輸出到同一個文件並不是一個好辦法。RollingFileAppender
用於切分文件日誌:
<appender name="dailyRollingFileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender"> <File>/data/log/app.log</File> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover --> <FileNamePattern>rest-demo.%d{yyyy-MM-dd}.log</FileNamePattern> <!-- keep 30 days' worth of history --> <maxHistory>30</maxHistory> </rollingPolicy> <encoder> <Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg %n</Pattern> </encoder> </appender>
其中重要的是rollingPolicy
的定義,上例中<FileNamePattern>rest-demo.%d{yyyy-MM-dd}.log</FileNamePattern>
定義了日誌的切分方式——把每一天的日誌歸檔到一個文件中,<maxHistory>30</maxHistory>
表示只保留最近30天的日誌,以防止日誌填滿整個磁盤空間。同理,可使用%d{yyyy-MM-dd_HH-mm}
來定義精確到分的日誌切分方式。
Sentry是一個統一的日誌跟蹤平臺,在傳統的日誌管理中,都是在服務器上經過tail
, vim
等工具查看日誌,而且不一樣的日誌位置也個不相同,而Sentry則是將這些日誌(主要是錯誤日誌)經過統一的接口收集起來,而且提供跟蹤、管理的功能,使得應用程序的錯誤、Bug可以即時被解決。
Sentry提供了Java庫——Raven Java,Java應用程序可以在捕獲異常後將其發送到Sentry服務器中,另外一方面它包含了各種日誌框架的支持,以Logbakc爲例:
<dependency> <groupId>net.kencochrane.raven</groupId> <artifactId>raven-logback</artifactId> <version>6.0.0</version> </dependency>
在logback.xml
中定義appender
:
<configuration> <appender name="Sentry" class="net.kencochrane.raven.logback.SentryAppender"> <dsn>https://publicKey:secretKey@host:port/1?options</dsn> <tags>tag1:value1,tag2:value2</tags> <!-- Optional, allows to select the ravenFactory --> <!--<ravenFactory>net.kencochrane.raven.DefaultRavenFactory</ravenFactory>--> </appender> <root level="warn"> <appender-ref ref="Sentry"/> </root> </configuration>
咱們推薦在這個<appender>
中加入<filter>
用於過濾ERROR
級別的日誌。
http://blog.csdn.net/xiaoyu411502/article/details/48295973
Spring Boot has no mandatory logging dependency, except for the commons-logging
API, of which there are many implementations to choose from. To use Logback you need to include it, and some bindings for commons-logging
on the classpath. The simplest way to do that is through the starter poms which all depend onspring-boot-starter-logging
. For a web application you only need spring-boot-starter-web
since it depends transitively on the logging starter. For example, using Maven:
<dependency>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
Spring Boot has a LoggingSystem
abstraction that attempts to configure logging based on the content of the classpath. If Logback is available it is the first choice.
If the only change you need to make to logging is to set the levels of various loggers then you can do that in application.properties
using the "logging.level" prefix, e.g.
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR
You can also set the location of a file to log to (in addition to the console) using "logging.file".
To configure the more fine-grained settings of a logging system you need to use the native configuration format supported by the LoggingSystem
in question. By default Spring Boot picks up the native configuration from its default location for the system (e.g. classpath:logback.xml
for Logback), but you can set the location of the config file using the "logging.config" property.
If you put a logback.xml
in the root of your classpath it will be picked up from there (or logback-spring.xml
to take advantage of the templating features provided by Boot). Spring Boot provides a default base configuration that you can include if you just want to set levels, e.g.
<?xml version="1.0" encoding="UTF-8"?>
<configuration> <include resource="org/springframework/boot/logging/logback/base.xml"/> <logger name="org.springframework.web" level="DEBUG"/> </configuration>
If you look at that base.xml
in the spring-boot jar, you will see that it uses some useful System properties which the LoggingSystem
takes care of creating for you. These are:
${PID}
the current process ID.${LOG_FILE}
if logging.file
was set in Boot’s external configuration.${LOG_PATH}
if logging.path
was set (representing a directory for log files to live in).${LOG_EXCEPTION_CONVERSION_WORD}
if logging.exception-conversion-word
was set in Boot’s external configuration.Spring Boot also provides some nice ANSI colour terminal output on a console (but not in a log file) using a custom Logback converter. See the default base.xml
configuration for details.
If Groovy is on the classpath you should be able to configure Logback with logback.groovy
as well (it will be given preference if present).
If you want to disable console logging and write output only to a file you need a custom logback-spring.xml
that imports file-appender.xml
but notconsole-appender.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<configuration> <include resource="org/springframework/boot/logging/logback/defaults.xml" /> <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}"/> <include resource="org/springframework/boot/logging/logback/file-appender.xml" /> <root level="INFO"> <appender-ref ref="FILE" /> </root> </configuration>
You also need to add logging.file
to your application.properties
:
logging.file=myapplication.log
http://docs.spring.io/spring-boot/docs/current/reference/html/howto-logging.html
下面是幾個經常使用的過濾器:
1,LevelFilter: 級別過濾器,根據日誌級別進行過濾。若是日誌級別等於配置級別,過濾器會根據onMath 和 onMismatch接收或拒絕日誌。
有如下子節點:
<level>:設置過濾級別
<onMatch>:用於配置符合過濾條件的操做
<onMismatch>:用於配置不符合過濾條件的操做
例如:將過濾器的日誌級別配置爲INFO,全部INFO級別的日誌交給appender處理,非INFO級別的日誌,被過濾掉。前面我已經舉過例子了,這裏就不作贅述了。
2,ThresholdFilter: 臨界值過濾器,過濾掉低於指定臨界值的日誌。當日志級別等於或高於臨界值時,過濾器返回NEUTRAL;當日志級別低於臨界值時,日誌會被拒絕。
3,EvaluatorFilter: 求值過濾器,評估、鑑別日誌是否符合指定條件。有一會兒節點:
<evaluator>:鑑別器,經常使用的鑑別器是JaninoEventEvaluato,也是默認的鑑別器,它以任意的java布爾值表達式做爲求值條件,求值條件在配置文件解釋過成功被動態編譯,布爾值表達式返回true就表示符合過濾條件。
evaluator有個子標籤<expression>,用於配置求值條件
<onMatch>,用於配置符合過濾條件的操做
<onMismatch>,用於配置不符合過濾條件的操做
http://blog.csdn.net/u011794238/article/details/50770557