Search code examples
javaspring-bootlogback

spring boot : stacktrace printed in console not in log file


Following is my logback.xml config in my springboot application.

<property name="LOG_DIR" value="${LOG_DIR}" />
<property name="LOG_FILE" value="${LOG_FILE}" />

<appender name="ROLLING_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_DIR}/${LOG_FILE}</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
        <fileNamePattern>${LOG_DIR}/${LOG_FILE}_old.%i.log</fileNamePattern>
        <minIndex>1</minIndex>
        <maxIndex>100</maxIndex>
    </rollingPolicy>

    <triggeringPolicy
            class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
        <maxFileSize>10MB</maxFileSize>
    </triggeringPolicy>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>
            %d{yyyy-MM-dd HH:mm:ss} - %msg%n
        </Pattern>
    </encoder>

</appender>

<root level="info">
    <appender-ref ref="ROLLING_LOG" />
</root>

Application is started with the following command

java -DLOG_DIR=/logs -DLOG_FILE=my.log -jar target/my.jar

I use @Sl4j in all my classes. All the logs are printed in the log file, except for exception's stacktrace (e.printStackTrace)., it is printed in console instead.

Not a duplicate post, gone through almost all the posts couldn't find proper answer

Appreciate any help

Thanks


Solution

  • As stated in the Javadoc:

    Prints this throwable and its backtrace to the standard error stream.

    So unless you log the exception through SLF4J, the stacktrace will not be printed in your file.

    If you do not control the call to printStackTrace, you can redirect the output of the java-command to append to a file.

    java -DLOG_DIR=/logs -DLOG_FILE=my.log -jar target/my.jar >> console.log 2>&1
    

    The above will append all text to a file console.log and redirect standard error stream to standard output stream.