20191112 Spring Boot official document learning (4.4)

4.4. Journal

Spring Boot used Commons Loggingfor all internal log, but logs realize that the underlying open state. To Java Util Logging, Log4J2and Logbackprovide a default configuration. In each case, the recorder is pre-configured to use the console output, while also providing an optional output file.

By default, if Starters, using Logback logging. Logback also include appropriate route, to ensure that use Java Util Logging, Commons Logging, Log4J or SLF4J dependent libraries can work.

4.4.1. Log Format

Spring Boot default log output similar to the following example:

2019-11-11 11:51:57.697  INFO 16640 --- [           main] study.hwj.springboot.MyApplication       : The following profiles are active: dev
2019-11-11 11:51:58.910  INFO 16640 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
  • Date and time: ms precision, easy to sort.
  • Log levels: ERROR, WARN, INFO, DEBUG, or TRACE.
  • Process ID.
  • --- Start delimiter to distinguish between actual log messages.
  • Thread Title: square brackets (for console output may be truncated).
  • Logger Name: This is usually the source class name (usually abbreviated).
  • Log messages.

Logback no FATAL level. It is mapped to ERROR.

4.4.2. Console output

The default logging configuration when the message is written to the message back to the console. By default, the record ERROR, WARN and INFO level messages. You can also use --debugto enable "Debug" mode flag to start the application.

Color coded output

If your terminal supports ANSI, use the color output to improve readability. You can set spring.output.ansi.enabledto override the automatic detection.

By using the %clrconfigured conversion color coded word. The simplest conversion example:

%clr(%5p)

The following table describes the mapping of color to the log level:

Log Level colour
FATAL red
ERROR red
WARN yellow
INFO green
DEBUG green
TRACE green

By its color or style to provide for the conversion of the option to specify that should be used. For example, to make the yellow text, use the following settings:

%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow}

It supports the following color and style:

  • blue
  • cyan
  • faint
  • green
  • magenta
  • red
  • yellow

4.4.3. File Output

By default, Spring Boot only logged to the console, do not write the log file. If in addition to the console output external want to write the log file is a need to set logging.file.nameor logging.file.pathattributes (e.g., in the application.properties).

Logging Properties:

logging.file.name logging.file.path Examples description
(No) (No) Console record only.
Specific file (No) my.log Written to the specified log file. The name can be the exact location, it can be relative to the current directory.
(No) Specific directory / Var / log Write spring.log specified directory. The name can be the exact location, it can be relative to the current directory.

The log file rotation reaches 10 MB, and as with console output, the default will be recorded ERROR, WARN, and INFO messages the case. You can use logging.file.max-sizethe properties to change the size limit. Unless you have set logging.file.max-historyattributes, otherwise the previous rotation of the archive files indefinitely. The total size of the log file can be used logging.file.total-size-capto set an upper limit. When the log archive total size exceeds the threshold, the backup will be deleted. To force to clear the log archiving when the application starts, use the logging.file.clean-history-on-startproperty.

Logging properties independent of the actual logging infrastructure. Results, Spring Boot specific configuration does not manage key (e.g. the Logback logback.configurationFile).

4.4.4. Log Level

All supported logging system may be provided in log level Spring Environment (e.g., by using the application.properties), , logging.level.<logger-name>=<level>where level is one TRACE, DEBUG, INFO, WARN, ERROR, FATAL or OFF. by using the root Logger can logging.level.rootbe configured.

The following example shows the default settings recorded in the log application.properties:

logging.level.root=warn
logging.level.org.springframework.web=debug
logging.level.org.hibernate=error

You can also use environment variables to set the logging level. For example, LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_WEB=DEBUGset org.springframework.webto DEBUG.

The above method applies only to package-level logging. Because loose environment variable bindings always converted to lower case, can not be arranged for a single class logging in this manner. When configuring the logging class, you can use the SPRING_APPLICATION_JSON variable.

4.4.5. Log Group

Records can be grouped together is often useful to be able to configure them simultaneously. For example, you can usually change the logging level all the Tomcat logger, but you are not likely to remember the top-level package.

To solve this problem, Spring Boot in Spring Environment allows you to define the logging group. For example, it is defined by the "tomcat" group is added to your way of its methods application.properties:

logging.group.tomcat=org.apache.catalina, org.apache.coyote, org.apache.tomcat

Once defined, you can use the line configuration changes in the group level for all loggers:

logging.level.tomcat=TRACE

Logging Group Spring Boot comprising predefined, they can be used directly:

name Loggers
web org.springframework.core.codec,org.springframework.http,org.springframework.web,org.springframework.boot.actuate.endpoint.web,org.springframework.boot.web.servlet.ServletContextInitializerBeans
sql org.springframework.jdbc.core,org.hibernate.SQL,org.jooq.tools.LoggerListener

4.4.6. Custom log configuration

By including the appropriate path in the class library to activate various logging system, and can be in the root directory path the class Spring Environment attributes or logging.configprovide the appropriate configuration file in the specified location to further customize various logging system.

You can use org.springframework.boot.logging.LoggingSystemto force Spring Boot logging system to use a specific system properties. The value should be the fully qualified class name LoggingSystem achieved. You can also completely disable Spring Boot logging configuration by using the value none.

-Dorg.springframework.boot.logging.LoggingSystem=none

Since logging was ApplicationContextbefore the creation initialized and therefore not from Spring @Configurationcontrol file @PropertySourceslogging. Change the logging system, or it is the only way to completely disable the system through the property.

Depending on the logging system load different configuration files:
Log System | log system configuration file
--- | ---
Logback | logback-spring.xml, logback-spring.groovy, logback.xml, or logback.groovy
Log4j2 | log4j2 or log4j2.xml -spring.xml
the JDK | (the Java Util Logging) the logging.properties

We recommend that you -springvariants for logging configuration (for example, logback-spring.xmlinstead logback.xml). If you use the standard configuration location, Spring will not fully control log initialization.

From "executable jar" runtime, Java Util Logging There are some known class loading problems that can cause problems. We recommend that you avoid using it as much as possible from the "executable jar" runtime.

To help customize the following table, some of the attributes in the Spring Environment may be disposed in the System properties:

Spring Environment System Property Remark
logging.exception-conversion-word LOG_EXCEPTION_CONVERSION_WORD Record convert word to use when abnormal.
logging.file.clean-history-on-start LOG_FILE_CLEAN_HISTORY_ON_START Whether to clear the archive log files at startup (if enabled LOG_FILE). (Only the default settings Logback supported.)
logging.file.name LOG_FILE If defined, it will use the default log configuration.
logging.file.max-size LOG_FILE_MAX_SIZE The maximum log file size (if enabled LOG_FILE). (Only the default settings Logback supported.)
logging.file.max-history LOG_FILE_MAX_HISTORY The maximum number of archived logs you want to keep (if enabled LOG_FILE) file. (Only the default settings Logback supported.)
logging.file.path LOG_PATH If defined, it will use the default log configuration.
logging.file.total-size-cap LOG_FILE_TOTAL_SIZE_CAP The total size of the log backups you want to keep (if enabled LOG_FILE). (Only the default settings Logback supported.)
logging.pattern.console CONSOLE_LOG_PATTERN Log mode (stdout) for use on the console. (Only the default settings Logback supported.)
logging.pattern.dateformat LOG_DATEFORMAT_PATTERN Additional mode recording date format. (Only the default settings Logback supported.)
logging.pattern.file FILE_LOG_PATTERN Log mode used in the file (if LOG_FILE enabled). (Only the default settings Logback supported.)
logging.pattern.level LOG_LEVEL_PATTERN The format used when rendering the logging level (default% 5p). (Only the default settings Logback supported.)
logging.pattern.rolling-file-name ROLLING_FILE_NAME_PATTERN Mode transition log file name (default $ {LOG_FILE}.% D {yyyy-MM-dd}.% I.gz). (Only the default settings Logback supported.)
PID PID The current process ID (if possible, and yet it is defined as OS environment variables will be found).

All logging system supported system properties can be used when parsing its configuration file. For an example, see the default configuration of the spring-boot.jar:

  • Logback
  • Log4j 2
  • Java Util logging

If you want to use placeholders in the logging properties, you should use the syntax syntax rather than the basic framework of the Spring Boot. It is noteworthy that, if you use Logback, they should be :used as a separator between property names to their default values, and should not be used :-.

您可以通过仅覆盖LOG_LEVEL_PATTERN(或使用Logback的logging.pattern.level)将MDC和其他临时内容添加到日志行。例如,如果使用logging.pattern.level=user:%X{user} %5p,则默认日志格式包含“ user”的MDC条目(如果存在),如以下示例所示。

2019-11-11 15:38:24.830 requestId:c60b9602-d273-4173-8ca2-2a3f2f2b438d  INFO 1980 --- [nio-8080-exec-1] study.hwj.springboot.MyController        : MyController...ttttt

MDC使用参考

4.4.7。Logback扩展

Spring Boot包含许多Logback扩展,可以帮助进行高级配置。您可以在logback-spring.xml配置文件中使用这些扩展名。

由于标准logback.xml配置文件加载太早,因此您不能在其中使用扩展名。您需要使用logback-spring.xml或定义一个logging.config属性。

这些扩展不能与Logback的配置扫描一起使用。如果尝试这样做,则对配置文件进行更改将导致类似于以下记录之一的错误:

ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for
[springProperty], current ElementPath is [[configuration][springProperty]]
ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for
[springProfile], current ElementPath is [[configuration][springProfile]]

特定于Profile的配置

使用<springProfile>标签,您可以根据激活的Spring Profiles选择包括或排除配置部分。Profile部分在<configuration>标签内的任何位置都受支持。使用name属性指定哪个 Profile 接受配置。<springProfile>标签可包含一个简单的 Profile 的名称(例如staging)或 Profile 表达式。Profile 表达式允许表达更复杂的 Profile 逻辑,例如production & (eu-central | eu-west)。有关更多详细信息,请参阅参考指南。以下清单显示了三个样本 Profiles:

<springProfile name="staging">
    <!-- configuration to be enabled when the "staging" profile is active -->
</springProfile>

<springProfile name="dev | staging">
    <!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
</springProfile>

<springProfile name="!production">
    <!-- configuration to be enabled when the "production" profile is not active -->
</springProfile>

环境特性

<springProperty>标签可以让你公开Spring Environment属性让Logback使用。如果您想从Logback配置中访问application.properties文件中的值,这样做会很有用。该标签的工作方式类似于Logback的标准<property>标签。但是,您无需直接指定value,而是指定source属性(来自Environment)。如果需要将属性存储在local范围之外的其他位置,则可以使用scope属性。如果需要fallback值(以防未在Environment中设置属性),则可以使用defaultValue属性。以下示例显示如何公开在Logback中使用的属性:

<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host"
        defaultValue="localhost"/>
<appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender">
    <remoteHost>${fluentHost}</remoteHost>
    ...
</appender>

source属性必须是短横线式语法(例如my.property-name)。但是,可以使用宽松规则将属性添加到Environment中。

Spring Boot日志原理

参考源码:
使用org.springframework.boot.context.logging.LoggingApplicationListener监听器监听多个事件:

ApplicationStartingEvent.class,
ApplicationEnvironmentPreparedEvent.class, 
ApplicationPreparedEvent.class, 
ContextClosedEvent.class,
ApplicationFailedEvent.class

在触发ApplicationStartingEvent事件时,初始化日志系统,参考org.springframework.boot.logging.LoggingSystem#get(java.lang.ClassLoader)

Guess you like

Origin www.cnblogs.com/huangwenjie/p/11846020.html