gary69
gary69

Reputation: 4230

How to write all log output to file spring boot

I'm using logback-spring.xml in a spring boot project. I want to log all uncaught exceptions to a file. Basically just direct the output from the console to a file. I've tried several variations of logback-spring.xml.

I tried this

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    <logger name="com.mine" level="WARN" additivity="false">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="FILE" />
    </logger>

    <root level="INFO">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="FILE">
            <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
                <resetJUL>true</resetJUL>
            </contextListener>
        </appender-ref>
    </root>
</configuration>

with this in my main method SLF4JBridgeHandler.install();

I've tried this from the spring docs

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <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/file-appender.xml" />
    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>
</configuration>

this is in my application.yml

logging:
  file: C:\dev\assessment-tool\logs\application.log
  config: classpath:logback-spring.xml

For these it will log all the start up logging messages but when an exception is thrown and not caught it goes to the console and doesn't show up in the log file. How can I make uncaught exceptions go to a log file?

Upvotes: 3

Views: 4220

Answers (1)

The problem is on the levels you're assigning to the loggers in the logback-spring.xml file.

According to the logback architecture documentation, (you can check it here) "The effective level for a given logger L, is equal to the first non-null level in its hierarchy, starting at L itself and proceeding upwards in the hierarchy towards the root logger".

You're assigning level "INFO" on your root logger, and level "WARN" on the logger "com.mine". None of them get "called" when there is an exception, ex: logger.error(Exception e).

One solution is assign the level "DEBUG" or "ERROR" to the logger "com.mine" or to the root logger, because they have attached the appender "FILE".

Upvotes: 2

Related Questions