如何关闭Spring Boot中的调试日志消息

45

我在 Spring Boot 的文档 (https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html) 中看到,你也可以在应用程序配置文件中指定 debug=true。

所以我猜如果我在 application.properties 中加上 debug=false 就能关闭调试日志。我尝试过了,但是没有起作用。接着我在同一篇文档中读到:

“日志系统会在应用生命周期的早期初始化,因此不会在通过 @PropertySource 注解加载的属性文件中找到日志属性。”

以及:

“由于日志在 ApplicationContext 创建之前就已初始化,因此无法从 Spring @Configuration 文件中的 @PropertySources 控制日志记录。”

还有:

“在可能的情况下,我们建议您使用 -spring 变量来配置日志记录。”因此,我在 src/main/resources 中添加了一个名为 log4j-spring.properties 的文件。

在这个文件中,我只添加了 debug=false 这一行,但是我仍然看到所有“当前日期”[main]DEBUG...信息。那么,我的问题是如何关闭 Spring Boot 应用程序中的调试消息,因为我将把应用程序部署到生产环境中。是否有一种推荐的方式通过 maven 实现呢?

2月12日添加:

两种主要方法: 1)使用 AnnotationConfigApplicationContext:

public class DemoAppNoBoot {
       public static void main(String[] args) {
              AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
                           BatchConfiguration.class);
              JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
              Job job = (Job) context.getBean("job");
               try {
                     JobExecution execution = jobLauncher.run(job, new JobParameters());
              } catch (Exception e) {
                     e.printStackTrace();
              }
       }
}

片段输出:

08:26:18.713 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
08:26:18.744 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
08:26:18.744 [main] DEBUG o.s.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
08:26:18.947 [main] INFO  o.s.c.a.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@532760d8: startup date [Fri Feb 12 08:26:18 CST 2016]; root of context hierarchy
08:26:18.947 [main] DEBUG o.s.c.a.AnnotationConfigApplicationContext - Bean factory for org.springframework.context.annotation.AnnotationConfigApplicationContext@532760d8: org.springframework.beans.factory.support.DefaultListableBeanFactory@50b494a6: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,batchConfiguration]; root of factory hierarchy
08:26:18.979 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 
...
08:26:32.560 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
08:26:32.560 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalScheduledAnnotationProcessor'
08:26:32.560 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor'
08:26:32.560 [main] DEBUG o.s.s.a.ScheduledAnnotationBeanPostProcessor - Could not find default TaskScheduler bean
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.scheduling.TaskScheduler] is defined     at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:372) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]      at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:332) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
...
08:26:33.529 [pool-1-thread-1] DEBUG o.s.jdbc.core.JdbcTemplate - Executing prepared SQL update
08:26:33.529 [pool-1-thread-1] DEBUG o.s.jdbc.core.JdbcTemplate - Executing prepared SQL statement [UPDATE BATCH_JOB_EXECUTION set START_TIME = ?, END_TIME = ?,  STATUS = ?, EXIT_CODE = ?, EXIT_MESSAGE = ?, VERSION = ?, CREATE_TIME = ?, LAST_UPDATED = ? where JOB_EXECUTION_ID = ? and VERSION = ?]
08:26:33.529 [pool-1-thread-1] DEBUG o.s.jdbc.core.JdbcTemplate - SQL update affected 1 rows
08:26:33.545 [pool-1-thread-1] DEBUG o.s.j.d.DataSourceTransactionManager - Initiating transaction commit
08:26:33.545 [pool-1-thread-1] DEBUG o.s.j.d.DataSourceTransactionManager - Committing JDBC transaction on Connection [org.hsqldb.jdbc.JDBCConnection@33bbce9c]
08:26:33.545 [pool-1-thread-1] DEBUG o.s.j.d.DataSourceTransactionManager - Releasing JDBC Connection [org.hsqldb.jdbc.JDBCConnection@33bbce9c] after transaction
08:26:33.545 [pool-1-thread-1] DEBUG o.s.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
08:26:33.545 [pool-1-thread-1] INFO  o.s.b.c.l.support.SimpleJobLauncher - Job: [SimpleJob: [name=job1]] completed with the following parameters: [{}] and the following status: [COMPLETED]
  1. 使用SpringApplication.run的主方法

    @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(BatchConfiguration.class, args); } }

: Spring Boot ::        (v1.3.1.RELEASE)
2016-02-12 08:02:36.145  INFO 12172 --- [           main] com.example.DemoApplication              : Starting DemoApplication on GH-VDIKCISV252 with PID 12172 (C:\STS\wsRestTemplate\demo\target\classes started by e049447 in C:\STS\wsRestTemplate\demo)
2016-02-12 08:02:36.145  INFO 12172 --- [           main] com.example.DemoApplication              : No active profile set, falling back to default profiles: default
2016-02-12 08:02:36.473  INFO 12172 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@4e4aea35: startup date [Fri Feb 12 08:02:36 CST 2016]; root of context hierarchy
2016-02-12 08:02:42.176  WARN 12172 --- [           main] o.s.c.a.ConfigurationClassEnhancer       : @Bean method ScopeConfiguration.stepScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean javadoc for complete details.
2016-02-12 08:02:42.349  WARN 12172 --- [           main] o.s.c.a.ConfigurationClassEnhancer       : @Bean method ScopeConfiguration.jobScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean javadoc for complete details.
2016-02-12 08:02:42.724  INFO 12172 --- [           main] o.s.j.d.e.EmbeddedDatabaseFactory        : Starting embedded database: url='jdbc:hsqldb:mem:testdb', username='sa'
2016-02-12 08:02:43.802  WARN 12172 --- [           main] o.s.b.c.l.AbstractListenerFactoryBean    : org.springframework.batch.item.ItemReader is an interface.  The implementing class will not be queried for annotation based listener configurations.  If using @StepScope on a @Bean method, be sure to return the implementing class so listner annotations can be used.
2016-02-12 08:02:44.990  INFO 12172 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executing SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql]
2016-02-12 08:02:45.179  INFO 12172 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executed SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql] in 189 ms.
2016-02-12 08:02:46.804  INFO 12172 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-02-12 08:02:46.868  INFO 12172 --- [           main] o.s.b.a.b.JobLauncherCommandLineRunner   : Running default command line with: []
2016-02-12 08:02:46.962  INFO 12172 --- [           main] o.s.b.c.r.s.JobRepositoryFactoryBean     : No database type set, using meta data indicating: HSQL
2016-02-12 08:02:47.040  INFO 12172 --- [pool-2-thread-1] o.s.b.c.r.s.JobRepositoryFactoryBean     : No database type set, using meta data indicating: HSQL
2016-02-12 08:02:47.243  INFO 12172 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : No TaskExecutor has been set, defaulting to synchronous executor.
2016-02-12 08:02:47.259  INFO 12172 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher      : No TaskExecutor has been set, defaulting to synchronous executor.
2016-02-12 08:02:47.321  INFO 12172 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=job1]] launched with the following parameters: [{run.id=1}]
2016-02-12 08:02:47.368  INFO 12172 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
2016-02-12 08:02:47.400  INFO 12172 --- [           main] com.example.CustomItemReader             : read method - collecting the MYAPP2 out file names
2016-02-12 08:02:47.525  INFO 12172 --- [           main] com.example.CustomItemReader             : read method - no file found
2016-02-12 08:02:47.556  INFO 12172 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=job1]] completed with the following parameters: [{run.id=1}] and the following status: [COMPLETED]
2016-02-12 08:02:47.556  INFO 12172 --- [           main] com.example.DemoApplication              : Started DemoApplication in 12.1 seconds (JVM running for 13.405)
2016-02-12 08:02:47.556  INFO 12172 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=job1]] launched with the following parameters: [{}]
2016-02-12 08:02:47.618  INFO 12172 --- [pool-2-thread-1] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
2016-02-12 08:02:47.634  INFO 12172 --- [pool-2-thread-1] com.example.CustomItemReader             : read method - collecting the MYAPP2 out file names
2016-02-12 08:02:47.634  INFO 12172 --- [pool-2-thread-1] com.example.CustomItemReader             : read method - no file found
2016-02-12 08:02:47.650  INFO 12172 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=job1]] completed with the following parameters: [{}] and the following status: [COMPLETED]

BatchConfiguration类

@Configuration
@ComponentScan("com.example")
@EnableBatchProcessing
@EnableAutoConfiguration
@EnableScheduling
@PropertySource("config.properties")
public class BatchConfiguration {
       @Autowired
       private JobBuilderFactory jobBuilderFactory;
       @Autowired
       private StepBuilderFactory stepBuilderFactory;
       @Bean
       public Step step1(ItemReader<String> reader,
                     ItemProcessor<String, String> processor, ItemWriter<String> writer) {
              return stepBuilderFactory.get("step1").<String, String> chunk(1)                          .reader(reader).processor(processor).writer(writer)
                           .allowStartIfComplete(true).build();
       }
//I took out the rest of BatchConfiguration class

应用程序属性(仅一行)

logging.level.*=OFF

备注:我不会展示config.properties文件,因为它仅包含用于业务逻辑的路径设置的几个属性名称

pom.xml

<?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.example</groupId>
       <artifactId>demo</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <packaging>jar</packaging>
       <name>demo</name>
       <description>Demo project for Spring Boot</description>
       <parent>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-parent</artifactId>
              <version>1.3.1.RELEASE</version>
              <relativePath /> <!-- lookup parent from repository -->
       </parent>
       <properties>
              <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
              <java.version>1.8</java.version>
              <spring.batch.version>3.0.6.RELEASE</spring.batch.version>
       </properties>
       <dependencies>
              <dependency>
                     <groupId>org.springframework.boot</groupId>
                     <artifactId>spring-boot-starter-batch</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>
                     <plugin>
                           <artifactId>maven-assembly-plugin</artifactId>
                           <configuration>
                                  <archive>
                                         <manifest>
                                                <mainClass>com.example.DemoAppNoBoot</mainClass>
                                         </manifest>
                                  </archive>
                                  <descriptorRefs>
                                         <descriptorRef>jar-with-dependencies</descriptorRef>
                                  </descriptorRefs>
                           </configuration>
                           <executions>
                                  <execution>
                                         <phase>install</phase>
                                         <goals>
                                                <goal>single</goal>
                                         </goals>
                                  </execution>
                           </executions>
                     </plugin>
                     <plugin>
                           <groupId>org.apache.maven.plugins</groupId>
                           <artifactId>maven-release-plugin</artifactId>
                           <version>2.5.1</version>
                           <configuration>
                                  <goals>install</goals>
                                  <preparationGoals>install</preparationGoals>
                           </configuration>
                     </plugin>
                     <plugin>
                           <groupId>org.apache.maven.plugins</groupId>
                           <artifactId>maven-jar-plugin</artifactId>
                           <configuration>
                                  <archive>
                                         <manifest>
                                                <addClasspath>true</addClasspath>
                                                <mainClass>com.example.DemoAppNoBoot</mainClass>
                                         </manifest>
                                  </archive>
                           </configuration>
                     </plugin>
              </plugins>
       </build>
</project>

Maven依赖项(与我的疑问相关的重要部分):

logback-classic-1.1.3.jar
logback-core-1.1.3.jar
slf4j-api-1.7.13.jar
log4j-over-slf4j-1.7.13.jar

1
请参阅 https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html#boot-features-custom-log-levels。基本上添加 logging.level.org.springframework=INFOlogging.level.root=INFO 就可以解决问题了。 - M. Deinum
1
在其默认配置中,Spring Boot 不会输出任何调试日志消息。您已经为您的应用程序添加了哪些与日志记录相关的配置? - Andy Wilkinson
请查看上述的Maven依赖:目前实际使用的是什么?是logback还是log4j?根据文档,我了解到logback被使用,或者至少它是最相关的日志库,因为文档中提到:"默认情况下,如果您使用'Starter POM',将使用Logback进行日志记录。" 假设我想要在生产环境(Unix)中更改输出的位置。我应该添加哪个文件名:logback-spring.xml还是log4j-spring.properties,以编辑LOG_FILE和LOG_PATH?我根据"其他属性从Spring环境传输到系统属性"的说法提出了我的问题。 - Jim C
7个回答

67
在application.properties文件中,您可以添加 'logging.level.*=LEVEL',其中“ LEVEL”是TRACE、DEBUG、INFO、WARN、ERROR、FATAL或OFF之一。 * 负责包/类。
例如:
logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR

这意味着根记录器的日志级别为WARN。org.springframework.web的日志级别为DEBUG,但所有Hibernate文件仅记录ERROR。

在您的情况下,您必须将logging.level.root设置为INFO、WARN、ERROR、FATAL或OFF中的一个级别,以关闭所有日志记录。

请参见https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html#boot-features-custom-log-levels


5
值得注意的是,为了避免任何调试日志输出,这些都不是必需的。Spring Boot的默认日志级别为info。 - Andy Wilkinson
1
我认为,由于我添加了Spring Boot库并在BatchConfiguration类中添加了@EnableAutoConfiguration,因此无论我是通过(1)“AnnotationConfigApplicationContext ... jobLauncher.run”还是(2)“@SpringBootApplication ... SpringApplication.run…”启动应用程序,我都在使用Spring Boot。我假设我错了。只有通过选项2启动才能有效使用Spring Boot。如果我错了,请纠正我。那么,为什么当我在Application.properties中更改logging.level.*=DEBUG时,在调用选项主方法时输出不会发生任何变化? - Jim C

10

在使用Spring Rest Docs和SpringMockMVC时,如果在Gradle中设置testLogging.showStandardStreams为true,则Spring会在控制台上大量输出信息和调试日志。我不得不使用Mkyong's solution,其中需要在src/test/resources中创建一个logback-test.xml文件,并在所选解决方案的顶部进行设置。可以使用log-level OFF、ERROR、WARN、DEBUG。

logback-test.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    <logger name="org.springframework" level="ERROR"/>
</configuration>

这正是我所需要的。 - takanuva15
谢谢,这个方法可以用,但是为了消除初始冗长的内容,它会破坏应用程序属性中整个Spring Boot配置。 - White_King

2

只需在您的应用程序主函数中添加这两行代码:

Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.ERROR);

必要的引入如下:

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.slf4j.LoggerFactory;

1
除了log4j.properties或log4j.xml文件外,您需要在maven pom.xml中添加这三个条目...添加log4j-acl工件立即为我解决了问题。它将来自commons logging的apache-commons-logging条目路由到log4j。
我不确定在grunt中如何处理这个问题,但是您需要的是桥接器。
    <!-- Log4J -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-jcl</artifactId>
        <version>${log4j.version}</version>
    </dependency> 

-1

我正在使用XML配置的Log4j2和Spring Boot。对于我来说,我需要指定logging子包,因此在<Loggers>块内:

    <Logger name="org.springframework.boot.autoconfigure.logging" level="error" />

-2

您还可以使用下面的模式在控制台中查看整洁的日志结果。

logging.pattern.console=%clr(%d{yy-MM-dd E HH:mm:ss.SSS}){blue} %clr(%-5p) %clr(%logger{0}){blue} %clr(%m){faint}%n

-9

点击断点图标并取消复选框。完成后重新运行。


1
我不明白这与问题有什么关系。 - Vladimir Stanciu
我该如何修改这个命令并与这个问题相关联?兄弟。 - Phearum KH
这并没有回答问题。 - Vishal_Kotecha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接