Why logback is not logging some lines with Spring

2019-09-15 04:58发布

问题:

I am trying to log some lines to a log files using logback. The file is correctly created and my console output is actually written in the log file.

Then, I inserted some logger.debug() instructions in my code, which I don't find in my log. Why?

I am using 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 includes logging.file=logs/mylog.log and this file is created.

Logback configuration is very easy and it should be correct and correctly placed (if I change this file, e.g. by introducing a log file name pattern, it works):

<?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>

Why I don't see my log instructions in my log file? Is it because I am building an InitializingBean? How can I log these lines?

回答1:

Its due to base.xml file which has root logging set at INFO level. Pls try this to get your debug logs :-

<?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>