'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 1:[1]

To print the StackTrace as in log file, the following method can be used.

Maven dependency in pom.xml

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>
String stacktrace = ExceptionUtils.getStackTrace(e); 

Using Core Java

StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
sw.toString() 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Muhammad Tariq