Logback相关知识汇总

来源:互联网 发布:苹果6当前网络不可用 编辑:程序博客网 时间:2024/05/19 19:40

spring boot中使用logback时一个一个配置文件示例:
(1)logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration><configuration  scan="true" scanPeriod="30 seconds">    <include resource="org/springframework/boot/logging/logback/base.xml"/>    <appender name="LOGSTASH" class="net.logstash.logback.appender.LogstashTcpSocketAppender">        <destination>192.168.100.4:8002</destination>        <encoder charset="UTF-8" class="net.logstash.logback.encoder.LogstashEncoder" />    </appender>     <!-- 设置日志级别 -->    <root level="INFO">                           <appender-ref ref="CONSOLE" />        <appender-ref ref="LOGSTASH" />    </root></configuration>

需要引入jar包:

<dependency> <groupId>net.logstash.logback</groupId>  <artifactId>logstash-logback-encoder</artifactId>  <version>4.7</version></dependency>

简单的:
(2)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
logback-spring.xml

<?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/log.log</file>        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">            <!-- daily rollover -->            <fileNamePattern>logs/log.%d{yyyy-MM-dd}.log</fileNamePattern>            <!-- 保留30天的历史日志 -->            <maxHistory>30</maxHistory>        </rollingPolicy>        <encoder>            <!--              <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>              -->            <pattern>${CUSTOM_LOG_PATTERN}</pattern>        </encoder>    </appender>    <appender name="ROLLING-FILE-WARN" class="ch.qos.logback.core.rolling.RollingFileAppender">        <file>logs/log-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/log-warn.%d{yyyy-MM-dd}.log</fileNamePattern>            <!-- 保留30天的历史日志 -->            <maxHistory>30</maxHistory>        </rollingPolicy>        <encoder>            <pattern>${CUSTOM_LOG_PATTERN}</pattern>        </encoder>    </appender>    <logger name="com.tangcheng" level="INFO" additivity="false">        <appender-ref ref="ROLLING-FILE-INFO"/>        <appender-ref ref="ROLLING-FILE-WARN"/>        <appender-ref ref="CONSOLE"/>    </logger>    <logger name="org.springframework">        <appender-ref ref="ROLLING-FILE-WARN"/>    </logger></configuration>

生成的日志文件:

一:根节点包含的属性:
scan:
当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。
scanPeriod:
设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。
debug:
当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。
例如:

<configuration scan="true" scanPeriod="60 seconds" debug="false">        <!-- 其他配置省略-->  </configuration>  

2.1设置上下文名称:
每个logger都关联到logger上下文,默认上下文名称为“default”。但可以使用设置成其他名字,用于区分不同应用程序的记录。一旦设置,不能修改。

<configuration scan="true" scanPeriod="60 seconds" debug="false">        <contextName>myAppName</contextName>        <!-- 其他配置省略-->  </configuration>  

2.2设置变量:

用来定义变量值的标签, 有两个属性,name和value;其中name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义变量后,可以使“${}”来使用变量。

例如使用定义上下文名称,然后在设置logger上下文时使用。

<configuration scan="true" scanPeriod="60 seconds" debug="false">        <property name="APP_Name" value="myAppName" />         <contextName>${APP_Name}</contextName>        <!-- 其他配置省略-->  </configuration>   

2.3设置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
可以包含零个或多个元素,标识这个appender将会添加到这个loger。

也是元素,但是它是根loger。只有一个level属性,应为已经被命名为”root”.
level:
用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,不能设置为INHERITED或者同义词NULL。
默认是DEBUG。
可以包含零个或多个元素,标识这个appender将会添加到这个loger。

spring boot默认配置的logback中的信息:

default.xml

<?xml version="1.0" encoding="UTF-8"?><!--Default logback configuration provided for import, equivalent to the programmaticinitialization 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 programmaticinitialization 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 programmaticinitialization 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.PostProcessorRegistrationDelegateBeanPostProcessorCheckerBeanconfigurationPropertiesRebinderAutoConfigurationoftype[classorg.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfigurationEnhancerBySpringCGLIB97204b4c]isnoteligibleforgettingprocessedbyallBeanPostProcessors(forexample:noteligibleforautoproxying)2016070407:37:30.482[restartedMain]ERRORorg.springframework.boot.SpringApplicationApplicationstartupfailedjava.lang.IllegalStateException:Logbackconfigurationerrordetected:ERRORinch.qos.logback.core.rolling.RollingFileAppender[FILE]Appender[FILE]failedtoappend.java.lang.NullPointerExceptionERRORinc.q.l.c.recovery.ResilientFileOutputStream@403418161IOfailurewhilewritingtofile[demo.log]java.io.IOException:StreamClosedatorg.springframework.boot.logging.logback.LogbackLoggingSystem.loadConfiguration(LogbackLoggingSystem.java:151)atorg.springframework.boot.logging.AbstractLoggingSystem.initializeWithConventions(AbstractLoggingSystem.java:71)atorg.springframework.boot.logging.AbstractLoggingSystem.initialize(AbstractLoggingSystem.java:49)atorg.springframework.boot.logging.logback.LogbackLoggingSystem.initialize(LogbackLoggingSystem.java:106)atorg.springframework.boot.logging.LoggingApplicationListener.initializeSystem(LoggingApplicationListener.java:301)atorg.springframework.boot.logging.LoggingApplicationListener.initialize(LoggingApplicationListener.java:253)atorg.springframework.boot.logging.LoggingApplicationListener.onApplicationEnvironmentPreparedEvent(LoggingApplicationListener.java:225)atorg.springframework.boot.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:201)atorg.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:163)atorg.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:136)atorg.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:119)atorg.springframework.boot.context.event.EventPublishingRunListener.publishEvent(EventPublishingRunListener.java:111)atorg.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:65)atorg.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54)atorg.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:330)atorg.springframework.boot.SpringApplication.run(SpringApplication.java:307)atorg.springframework.boot.SpringApplication.run(SpringApplication.java:1191)atorg.springframework.boot.SpringApplication.run(SpringApplication.java:1180)atcom.DemoApplication.main(DemoApplication.java:17)atsun.reflect.NativeMethodAccessorImpl.invoke0(NativeMethod)atsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)atsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)atjava.lang.reflect.Method.invoke(Method.java:498)atorg.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)2016070407:37:30.486[restartedMain]INFOo.s.b.logging.ClasspathLoggingApplicationListenerApplicationfailedtostartwithclasspath:[file:/D:/workspace/demo/target/classes/,file:/D:/workspace/common/target/classes/]2016070407:51:03.820[restartedMain]INFOo.s.c.a.AnnotationConfigApplicationContextRefreshingorg.springframework.context.annotation.AnnotationConfigApplicationContext@1237898e:startupdate[MonJul0407:51:03CST2016];rootofcontexthierarchy2016070407:51:04.568[restartedMain]INFOo.s.b.f.a.AutowiredAnnotationBeanPostProcessorJSR330javax.inject.Injectannotationfoundandsupportedforautowiring2016070407:51:04.623[restartedMain]INFOo.s.c.s.PostProcessorRegistrationDelegateBeanPostProcessorChecker - 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)


(2)

… the rest of the configuration file

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

效果图:

<?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演示了基于大小和时间的记录文件归档。

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
[Note]
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:

Level Color
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.

[Note]
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:

Logging System Customization
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

[Note]
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.

[Warning]
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:

原创粉丝点击