【问题标题】:Why logback is not logging some lines with Spring Boot?为什么 logback 没有使用 Spring Boot 记录一些行?
【发布时间】:2024-01-16 11:45:01
【问题描述】:

我正在尝试使用 logback 将一些行记录到日志文件中。该文件已正确创建,我的控制台输出实际上已写入日志文件。

然后,我在我的代码中插入了一些 logger.debug() 指令,但我在日志中找不到这些指令。为什么?

我正在使用 Spring Boot:

@SpringBootApplication
public class MyApplication {

    private static final Logger logger =
            LoggerFactory.getLogger(MyApplication.class);

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

    @Bean
    InitializingBean myInitializer(final IdentityService identityService) {
        return new InitializingBean() {
            public void afterPropertiesSet() throws Exception {
                logger.debug("Preparing things...");
                if (someCondition) {
                    doSomething();
                    logger.debug("Done something.");
                } else {
                    doSomethingElse();
                    logger.debug("Done something else.");
                }

            }
        };
    }
}

application.properties 包含logging.file=logs/mylog.log 并创建此文件。

Logback 配置非常简单,它应该是正确和正确放置的(如果我更改此文件,例如通过引入日志文件名模式,它可以工作):

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

为什么在我的日志文件中看不到我的日志说明?是因为我正在构建一个 InitializingBean 吗?如何记录这些行?

【问题讨论】:

    标签: java logging spring-boot logback


    【解决方案1】:

    这是由于 base.xml 文件在 INFO 级别设置了根日志记录。请尝试这个来获取您的调试日志:-

    <?xml version="1.0" encoding="UTF-8"?>    
    <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" />
        <logger name="org.springframework.web" level="DEBUG"/>
        <root level="DEBUG">
            <appender-ref ref="CONSOLE" />
            <appender-ref ref="FILE" />
        </root>
    </included>
    

    【讨论】:

    • 谢谢,我尝试添加 并且它工作正常,但它有点太多的日志记录。有没有办法提高日志记录级别以仅针对我的课程进行调试?
    • 好的,我只是在我的应用程序属性中添加了 logging.level.com.lh.batactiviti=DEBUG。在了解问题出在 base.xml 之后就足够了
    最近更新 更多