Logback 专题
?
logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration><!--<pattern>%d{yyyy-MM-dd HH:mm:ss} [%level] - %msg%nLogger: %loggerClass: %classFile: %fileCaller: %callerLine: %lineMessage: %mMethod: %MRelative: %relativeThread: %threadException: %exxException: %xExnopException: %nopexrException: %rExMarker: %markernewline:%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.
?
Example: Additivity flag (logback-examples/src/main/resources/chapters/configuration/additivityFlag.xml)
<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.
https://logback.qos.ch/manual/configuration.html
?
File inclusion
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)
<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)
<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.
The contents to include can be referenced as a file, as a resource, or as a URL.
- As a file:
To include a file use the?file?attribute. You can use relative paths but note that the current directory is defined by the application and is not necessarily related to the path of the configuration file. -
As a resource:
To include a resource, i.e a file found on the class path, use the?resource?attribute.
- As a file:
As a URL:
To include the contents of a URL use the?url?attribute.
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:
| 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.
https://logback.qos.ch/manual/architecture.html
?
?
?
| 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.
| %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.
| [%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
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)文件中定義即可
示例:
?
如果要將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><triggeringPolicyclass="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"><MaxFileSize>10MB</MaxFileSize></triggeringPolicy></appender> </included>base.xml屬于集上面于大成者,引用上面的default.xml,file-appender.xml,console-appender.xml
因為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:
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.
?
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.
?
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.
Binary com
https://www.slf4j.org/manual.html?
?
?
?
例如:%-4relative 表示,將輸出從程序啟動到創建日志記錄的時間 進行左對齊 且最小寬度為4
格式修飾符,與轉換符共同使用:
可選的格式修飾符位于“%”和轉換符之間。
第一個可選修飾符是左對齊 標志,符號是減號“-”;
接著是可選的最小寬度 修飾符,用十進制數表示。如果字符小于最小寬度,則左填充或右填充,默認是左填充(即右對齊),填充符為空格。如果字符大于最小寬度,字符永遠不會被截斷。最大寬度 修飾符,符號是點號"."后面加十進制數。如果字符大于最大寬度,則從前面截斷。點符號“.”后面加減號“-”在加數字,表示從尾部截斷。
出現上面報錯時,很有可能是因為maxFileSize設置有不合理(一般是太小),文件rename太快,導致異常發生。
如果想了解詳解信息,可以查看logback的日志打印,可以把logback的debug打開:(1)
(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>?
Appenders accumulate
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
?
效果圖:
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 typech.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%nLogger: %loggerClass: %classFile: %fileCaller: %callerLine: %lineMessage: %mMethod: %MRelative: %relativeThread: %threadException: %exxException: %xExnopException: %nopexrException: %rExMarker: %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演示了基于大小和時間的記錄文件歸檔。
layout格式修飾符
如給定的一個格式:%-5p [%t]: %m%n中,并沒有明確的分隔轉換字符和普通文本的字符存在。PatternLayout能自己區分普通文本和轉換字符。其中%-5p是日志的調用級別。事件是左對齊的,5個字符寬度。
格式修飾符,放在%和轉換符之間。?第一個可選的格式修飾符是左對齊(-);第二個可選的格式修飾符是字段最小寬度。一個整數。表示輸出的最小字符數。如果數據未達到指定最小大小,那么它將以左填充(默認)或者右填充方式(左對齊情況下只能使用右填充了)。用空格填充,直到達到最小寬度。如果大于指定最小寬度,不會被截斷?。當然可以指定最大字符數,使用.符號加數字表示最大字符數。如果大于指定長度,多余的字符會被刪除。它是從前面刪除,而不是從后面刪除的。如最大字符是8個,數據有10個字符,那么前面兩個字符會被刪除。?
%20c?右對齊,最少20字符,沒有左邊用空格填充?
%-20c?左對齊,最少20字符,沒有右邊用空格填充?
%.30c?右對齊,最多30字符,超過左邊的截取掉?
%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:
- The number has to be an integer
- You can add 'KB', 'MB' or 'GB' after the number.
Here are some correct values: 500KB, 15MB, 2GB.
No?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:
- SizeBasedTriggeringPolicy
- TimeBasedRollingPolicy
Please note that the?TimeBasedRollingPolicy?is a TriggeringPolicy?and?and?RollingPolicy?at the same time.
Missing integer token, that is %i, in FileNamePattern [...].
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
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
?
https://yq.aliyun.com/articles/25530
26.2?Console output
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?debug=true?in your?application.properties. |
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.
26.2.1?Color-coded output
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:
| FATAL | Red |
| ERROR | Red |
| WARN | Yellow |
| INFO | Green |
| DEBUG | Green |
| TRACE | 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
?
26.5?Custom log configuration
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?ApplicationContext?is created, it isn’t possible to control logging from?@PropertySources?in Spring@Configuration?files. System properties and the conventional Spring Boot external configuration files work just fine.) |
Depending on your logging system, the following files will be loaded:
| Logback | logback-spring.xml,?logback-spring.groovy,?logback.xml?or?logback.groovy |
| Log4j | log4j-spring.properties,?log4j-spring.xml,?log4j.properties?or?log4j.xml |
| Log4j2 | log4j2-spring.xml?or?log4j2.xml |
| JDK (Java Util Logging) | logging.properties |
| When possible we recommend that you use the?-spring?variants for your logging configuration (for example?logback-spring.xml?rather thanlogback.xml). If you use standard configuration locations, Spring cannot completely control log initialization. |
| 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:
| logging.exception-conversion-word | LOG_EXCEPTION_CONVERSION_WORD | The conversion word that’s used when logging exceptions. |
| logging.file | LOG_FILE | Used in default log configuration if defined. |
| logging.path | LOG_PATH | Used in default log configuration if defined. |
| logging.pattern.console | CONSOLE_LOG_PATTERN | The log pattern to use on the console (stdout). (Not supported with JDK logger.) |
| logging.pattern.file | FILE_LOG_PATTERN | The log pattern to use in a file (if LOG_FILE enabled). (Not supported with JDK logger.) |
| logging.pattern.level | LOG_LEVEL_PATTERN | The format to use to render the log level (default?%5p). (Thelogging.pattern.level?form is only supported by Logback.) |
| PID | PID | 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?:?as the delimiter between a property name and its default value and not?:-. ? |
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通配符,可以直接查看幫助文檔。
3、Level 有效級別
Logger可以被分配級別。級別包括:TRACE、DEBUG、INFO、WARN和ERROR,定義于ch.qos.logback.classic.Level類。程序會打印高于或等于所設置級別的日志,設置的日志等級越高,打印出來的日志就越少。如果設置級別為INFO,則優先級高于等于INFO級別(如:INFO、 WARN、ERROR)的日志信息將可以被輸出,小于該級別的如DEBUG將不會被輸出。為確保所有logger都能夠最終繼承一個級別,根logger總是有級別,默認情況下,這個級別是DEBUG
4、 三值邏輯
Logback的過濾器基于三值邏輯(ternary logic),允許把它們組裝或成鏈,從而組成任意的復合過濾策略。過濾器很大程度上受到Linux的iptables啟發。這里的所謂三值邏輯是說,過濾器的返回值只能是ACCEPT、DENY和NEUTRAL的其中一個。
如果返回DENY,那么記錄事件立即被拋棄,不再經過剩余過濾器;
如果返回NEUTRAL,那么有序列表里的下一個過濾器會接著處理記錄事件;
如果返回ACCEPT,那么記錄事件被立即處理,不再經過剩余過濾器。
5、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
?
SizeBasedTriggeringPolicy
sizebasedtriggeringpolicy 監控當前使用的日志文件的大小。當文件大于指定的大小時,將會通過rollingfileappender觸發滾動事件。它只接受一個屬性,maxfilesize。默認值是10MB。maxfilesize屬性可以以KB,MB,GB作為單位,如5000000.5000KB,5MB ,5GB,前面三個值是相等的。舉例如下,文件大小設置為5MB。 <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 , 配置如下:
將logback.xml 放置到web工程的classes目路下,運行項目
http://www.cnblogs.com/dragonflyyi/p/4245250.html
?
LogBack可以通過編程式或以XML、Groovy格式配置,原來使用log4j的用戶可以通過屬性轉換器將log4j.properties轉換成logback.xml文件。我在使用這個轉換器的時候,能轉換成功,但是在Web-App中日志輸出的有點小問題,后來就自己寫logback.xml文件,LogBack讀取配置或屬性文件的步驟: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>?
?
?
一、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>這樣依賴包全部自動下載了!
二、logback取代 log4j的理由:
Logback和log4j是非常相似的,如果你對log4j很熟悉,那對logback很快就會得心應手。下面列了logback相對于log4j的一些優點:
1、更快的實現 Logback的內核重寫了,在一些關鍵執行路徑上性能提升10倍以上。而且logback不僅性能提升了,初始化內存加載也更小了。
2、非常充分的測試 Logback經過了幾年,數不清小時的測試。Logback的測試完全不同級別的。在作者的觀點,這是簡單重要的原因選擇logback而不是log4j。
3、Logback-classic非常自然實現了SLF4j Logback-classic實現了 SLF4j。在使用SLF4j中,你都感覺不到logback-classic。而且因為logback-classic非常自然地實現了SLF4J, 所 以切換到log4j或者其他,非常容易,只需要提供成另一個jar包就OK,根本不需要去動那些通過SLF4JAPI實現的代碼。
4、非常充分的文檔 官方網站有兩百多頁的文檔。
5、自動重新加載配置文件 當配置文件修改了,Logback-classic能自動重新加載配置文件。掃描過程快且安全,它并不需要另外創建一個掃描線程。這個技術充分保證了應用程序能跑得很歡在JEE環境里面。
6、Lilith Lilith是log事件的觀察者,和log4j的chainsaw類似。而lilith還能處理大數量的log數據 。
7、謹慎的模式和非常友好的恢復 在謹慎模式下,多個FileAppender實例跑在多個JVM下,能 夠安全地寫道同一個日志文件。RollingFileAppender會有些限制。Logback的FileAppender和它的子類包括 RollingFileAppender能夠非常友好地從I/O異常中恢復。
8、配置文件可以處理不同的情況 開發人員經常需要判斷不同的Logback配置文件在不同的環境下(開發,測試,生產)。而這些配置文件僅僅只有一些很小的不同,可以通過,和來實現,這樣一個配置文件就可以適應多個環境。
9、Filters(過濾器) 有些時候,需要診斷一個問題,需要打出日志。在log4j,只有降低日志級別,不過這樣會打出大量的日志,會影響應用性能。在Logback,你可以繼續 保持那個日志級別而除掉某種特殊情況,如alice這個用戶登錄,她的日志將打在DEBUG級別而其他用戶可以繼續打在WARN級別。要實現這個功能只需 加4行XML配置。可以參考MDCFIlter 。
10、SiftingAppender(一個非常多功能的Appender) 它可以用來分割日志文件根據任何一個給定的運行參數。如,SiftingAppender能夠區別日志事件跟進用戶的Session,然后每個用戶會有一個日志文件。
11、自動壓縮已經打出來的log RollingFileAppender在產生新文件的時候,會自動壓縮已經打出來的日志文件。壓縮是個異步過程,所以甚至對于大的日志文件,在壓縮過程中應用不會受任何影響。
12、堆棧樹帶有包版本 Logback在打出堆棧樹日志時,會帶上包的數據。
13、自動去除舊的日志文件 通過設置TimeBasedRollingPolicy或者SizeAndTimeBasedFNATP的maxHistory屬性,你可以控制已經產生日志文件的最大數量。如果設置maxHistory 12,那那些log文件超過12個月的都會被自動移除。
總之,logback比log4j太優秀了,讓我們的應用全部建立logback上吧 !
三、Logback的配置介紹
1、Logger、appender及layout
Logger作為日志的記錄器,把它關聯到應用的對應的context上后,主要用于存放日志對象,也可以定義日志類型、級別。
Appender主要用于指定日志輸出的目的地,目的地可以是控制臺、文件、遠程套接字服務器、 MySQL、 PostreSQL、 Oracle和其他數據庫、 JMS和遠程UNIX Syslog守護進程等。
Layout 負責把事件轉換成字符串,格式化的日志信息的輸出。
2、logger context
各個logger 都被關聯到一個 LoggerContext,LoggerContext負責制造logger,也負責以樹結構排列各 logger。其他所有logger也通過org.slf4j.LoggerFactory 類的靜態方法getLogger取得。 getLogger方法以 logger 名稱為參數。用同一名字調用LoggerFactory.getLogger 方法所得到的永遠都是同一個logger對象的引用。
3、有效級別及級別的繼承
Logger 可以被分配級別。級別包括:TRACE、DEBUG、INFO、WARN 和 ERROR,定義于 ch.qos.logback.classic.Level類。如果 logger沒有被分配級別,那么它將從有被分配級別的最近的祖先那里繼承級別。root logger 默認級別是 DEBUG。
4、打印方法與基本的選擇規則
打印方法決定記錄請求的級別。例如,如果 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入門實踐
一、簡介
LogBack是一個日志框架,它是Log4j作者Ceki的又一個日志組件。
?
LogBack,Slf4j,Log4j之間的關系
? ? 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的結構
LogBack分為3個組件,logback-core, logback-classic 和 logback-access。
其中logback-core提供了LogBack的核心功能,是另外兩個組件的基礎。
logback-classic則實現了Slf4j的API,所以當想配合Slf4j使用時,則需要引入這個包。
logback-access是為了集成Servlet環境而準備的,可提供HTTP-access的日志接口。
?
Log的行為級別
OFF、
FATAL、
ERROR、
WARN、
INFO、
DEBUG、
ALL
從下向上,當選擇了其中一個級別,則該級別向下的行為是不會被打印出來。
舉個例子,當選擇了INFO級別,則INFO以下的行為則不會被打印出來。
?
二、slf4j與logback結合使用原理
我們從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與logback結合使用實踐
第一步引入jar包
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>?
第二步編寫簡單的logback配置文件
<?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" underthe key "bySecond" into the logger context. This value will beavailable 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 typech.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> {@Overridepublic 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
Spring Boot Logback應用日志
SLF4J與Logback簡介
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 Logging
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的日志級別。
ConsoleAppender
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.LoggingResponseFilterRollingFileAppender
另一種常見的日志輸出到文件,隨著應用的運行時間越來越長,日志也會增長的越來越多,將他們輸出到同一個文件并非一個好辦法。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
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
72.?Logging
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=ERRORYou 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.
72.1?Configure Logback for logging
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.xmlconfiguration 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).
72.1.1?Configure logback for file only output
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.loghttp://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
轉載于:https://www.cnblogs.com/softidea/p/5642174.html
總結
以上是生活随笔為你收集整理的Logback 专题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 广汽传祺新一代 M8 大师车型正式上市,
- 下一篇: ajax中success函数无法改变全局