Logback相关知识汇总
Posted 沧海一滴
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Logback相关知识汇总相关的知识,希望对你有一定的参考价值。
logback-spring.xml
<?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.
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.
<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> </springboot整合logback集成elk实现日志的汇总分析统计和检索功能spring boot 性能测试工具汇总logback异步日志分析
spring boot 性能测试工具汇总logback异步日志分析