Spring Boot 日志指南

Spring Boot 日志指南

原文: https://howtodoinjava.com/spring-boot2/logging/spring-boot-logging-configurations/

登录 Spring Boot 非常灵活且易于配置。 Spring Boot 通过一些简单的配置即可支持各种日志记录提供程序。 在本教程中,我们将介绍 Spring Boot 支持的各种日志记录选项和配置。

1. 默认零配置日志

启用了 Spring Boot 活动的日志记录由spring-boot-starter-logging工件确定,并且它是自动配置,可启用任何受支持的日志记录提供程序(java.util.loggingLog4J2Logback)基于提供的配置。

如果我们不提供任何特定于日志记录的配置,我们仍将看到打印在“控制台”中的日志。 这是因为在 Spring Boot 中使用 Logback默认日志支持

Spring Boot 的内部日志记录是用 Apache Commons Logging 编写的,因此它是唯一且唯一的依赖项。 直到启动 1.x,我们都必须手动导入它。 从运行 2.x 开始,它会进行过渡下载。 更准确地说,spring-boot-starter-web取决于spring-boot-starter-logging,它为我们拉入spring-jcl

Spring Boot 自动配置提供使用Logback的默认日志记录,并且这些配置文件中提供了默认配置。

1.1. 添加日志语句

要在应用程序代码中添加日志语句,请使用 SLF4J 中的org.slf4j.Loggerorg.slf4j.LoggerFactory。 它提供了许多有用的日志记录方法,也使日志记录实现与应用程序脱钩。

Application.java

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application 
{
	private static final Logger LOGGER=LoggerFactory.getLogger(Application.class);

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);

		LOGGER.info("Simple log statement with inputs {}, {} and {}", 1,2,3);
	}
}

Console

2019-07-28 12:16:57.129  INFO 3416 --- [main] 
com.howtodoinjava.demo.Application: Simple log statement with inputs 1, 2 and 3

1.2. 记录级别

Logback 支持将ERRORWARNINFODEBUGTRACE作为日志记录级别。 默认情况下,日志记录级别设置为INFO。 这意味着代码DEBUGTRACE消息不可见。

要启用调试或跟踪日志记录,我们可以在application.properties文件中设置日志记录级别。 另外,我们可以在启动应用程序时在命令行上传递 – debug或 – trace参数。

Configuration

# In properties file
debug=true

# In Console
$ java -jar target/my-app-0.0.1-SNAPSHOT.jar --trace

我们也可以将日志记录级别应用于特定的软件包。 可以在控制台或application.properties文件中完成。

Configuration

# In Console
-Dlogging.level.org.springframework=ERROR 
-Dlogging.level.com.howtodoinjava=TRACE

# In properties file
logging.level.org.springframework=ERROR 
logging.level.com.howtodoinjava=TRACE

如果使用不同的日志级别多次定义了程序包的日志级别,则将使用最低级别。 TRACE最低,ERROR最高。

1.3. 日志格式

defaults.xml文件中提到了默认的日志语句格式。

defaults.xml

<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{${LOG_DATEFORMAT_PATTERN:-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{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} 
${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>

输出以下信息。

  • 日期和时间:毫秒精度,易于排序。
  • 日志级别ERRORWARNINFODEBUGTRACE
  • 进程 ID。
  • ---分隔符用于区分实际日志消息的开始。
  • 线程名称:放在方括号中(对于控制台输出,可能会被截断)。
  • 记录器名称:这通常是源类名称(通常缩写)。
  • 日志消息。

自定义日志格式,请使用logging.pattern.consolelogging.pattern.file属性。

application.properties

# Logging pattern for the console
logging.pattern.console= %d{yyyy-MM-dd HH:mm:ss} - %logger{36} - %msg%n

# Logging pattern for file
logging.pattern.file= %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%

1.4. 记录到文件

默认情况下,spring boot 日志仅记录到控制台。 如果要启用文件记录,可以使用简单属性logging.filelogging.path轻松进行。

使用logging.path时,它将在上述包中创建一个名为spring.log的文件。

application.properties

# Output to a temp_folder/file
logging.file=c:/temp/application.log

#logging.path=/my-folder/

# Logging pattern for file
logging.pattern.file= %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%

2. Logback 日志记录

对于大多数用例,默认日志记录已经足够了。 但是有时在企业应用程序中,我们需要对具有其他复杂需求的日志进行更好的控制。 在那种情况下,具有专用的日志日志配置是合适的。

默认情况下,Spring Boot 使用 logback,因此要自定义其行为,我们只需要在类路径中添加logback.xml并定义该文件的自定义即可。

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

	<property name="LOG_LOCATION" value="c:/temp" />

	<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
         	<pattern>%d{yyyy-MM-dd HH:mm:ss} - %logger{36} - %msg%n</pattern>
      	</encoder>
	</appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
      	<File>{LOG_LOCATION}/mylog.log</File>
      	<encoder>
	         <pattern>%d{yyyy-MM-dd HH:mm:ss} - %logger{36} - %msg%n</pattern>
	    </encoder>
	    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_LOCATION}/archived/mylog-%d{yyyy-MM-dd}.%i.log
            </fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
   	</appender> 

   	<root level="INFO">
    	<appender-ref ref="CONSOLE"/>
    	<appender-ref ref="FILE"/>
   	</root>

   	<!-- Application logs at trace level -->
   	<logger name="com.howtodoinjava" level="trace" additivity="false">
        <appender-ref ref="RollingFile" />
        <appender-ref ref="Console" />
    </logger>

</configuration>

3. Log4j2 记录

步骤 1:排除 logback,并包括 log4j2

如前所述,spring boot 使用 logback 作为默认值。 因此,如果我们必须使用其他任何日志记录框架,例如 log4j2,我们必须从应用程序的类路径中排除登录。 另外,将spring-boot-starter-log4j2添加到类路径。

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

步骤 2:添加 log4j2 配置文件

现在,在类路径(通常在资源文件夹中)中添加特定于 log4j2 的配置文件。 可以将其命名为以下任意一种:

  • log4j2-spring.xml
  • log4j2.xml

如果我们在其他任何文件(例如log4j2.propertiesapplogs.xml等)中都有日志日志配置,则可以使用logging.file属性指定其路径application.properties文件。

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} %p %m%n</Property>
        <Property name="APP_LOG_ROOT">c:/temp</Property>
    </Properties>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="${LOG_PATTERN}" />
        </Console>

        <RollingFile name="file"
            fileName="${APP_LOG_ROOT}/SpringBoot2App/application.log"
            filePattern="${APP_LOG_ROOT}/SpringBoot2App/application-%d{yyyy-MM-dd}-%i.log">
            <PatternLayout pattern="${LOG_PATTERN}" />
            <Policies>
                <SizeBasedTriggeringPolicy size="19500KB" />
            </Policies>
            <DefaultRolloverStrategy max="1" />
        </RollingFile>

    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="console" />
            <AppenderRef ref="file" />
        </Root>
    </Loggers>
</Configuration>

步骤 3:有或没有 Slf4j

默认情况下,如果您正在使用 SLF4J 记录器类,即org.slf4j.Loggerorg.slf4j.LoggerFactory,则无需更改应用程序代码,所有日志语句将继续在目标附加程序中打印。

如果您打算仅使用 log4j2 特定的类,请使用org.apache.logging.log4j.Loggerorg.apache.logging.log4j.LogManager

我将建议使用 SLF4J 记录器类。

SLF4J logger classes

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SpringBootApplication
public class Application 
{
	private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);

	public static void main(String[] args) {		
		SpringApplication.run(Application.class, args);

		LOGGER.info("Simple log statement with inputs {}, {} and {}", 1,2,3);
	}
}

LOG4J2 logger classes

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

@SpringBootApplication
public class Application 
{
	private static Logger LOGGER = LogManager.getLogger(Application.class);

	public static void main(String[] args) {		
		SpringApplication.run(Application.class, args);

		LOGGER.info("Simple log statement with inputs 1, 2 and 3");
	}
}

4. 有关 Spring Boot 日志记录的更多示例

  1. Spring Boot 2 log4j2.xml示例
  2. Spring Boot 2 log4j2.properties示例
  3. application.yml和 Spring Boot 日志
  4. application.properties和 Spring 日志
  5. Tomcat 和 Jetty 的 SpringBoot 嵌入式服务器日志配置
  6. AspectJ AOP 和 Spring Boot 性能日志
  7. Lombok 和 Spring Boot 日志
  8. Spring Boot 多个日志文件示例
  9. Spring Boot 控制台日志配置示例
  10. Spring 配置文件特定的日志示例

请问一下您与 Spring Boot 中的日志配置有关的问题

学习愉快!