poyger
poyger

Reputation: 666

Spring boot startup logs to file

Is it anyway to send startup logs to file, right now all logs up to the statement "Started Application in...." goes to stdout, I want all logging to file.

My logback config:

<?xml version="1.0" encoding="UTF-8"?>
       <configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <property name="LOG_FILE" value="logs/app${PID}.log"/>

    <appender name="AI-APPENDER"
              class="com.microsoft.applicationinsights.logback.ApplicationInsightsAppender">
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
        </encoder>
        <file>${LOG_FILE}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz</fileNamePattern>
            <maxFileSize>${LOG_FILE_MAX_SIZE:-10MB}</maxFileSize>
            <maxHistory>30</maxHistory>
        </rollingPolicy>
    </appender>

    <root level="INFO">
        <appender-ref ref="FILE"/>
        <appender-ref ref="AI-APPENDER"/>
    </root>
</configuration>

Upvotes: 1

Views: 3001

Answers (1)

pcoates
pcoates

Reputation: 2307

You need to configure your logging framework. Assuming you're just using the default from spring-boot then that's LogBack. So have a look at their docs or have a search, there are many useful resources (like this one)

If you add a logback.xml file with the following content to your resources folder you should get logging to both console and file (called application.log) in the same format as you now see for just console.

<configuration>

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>application.log</file>

    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="info">
    <appender-ref ref="FILE" />
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

You probably want to use a RollingFileAppender as this will allow you to create new files when the log file gets big.

Upvotes: 1

Related Questions