Home > front end >  How to clear log file before executing spring boot app?
How to clear log file before executing spring boot app?

Time:01-04

I have been using the default spring logging configuration where I only specify filename in the application.properties file.

logging.file.name=app.log

But this by default appends logs when I start the application from cmd line "java -jar abc.jar"

I tried to search for the property which clears the file before starting application every time but couldn't find it. How should I clear the log file before starting the app?

CodePudding user response:

Spring Boot uses Logback framework as as a default Logger. You can use environnement variable via application.properties file to set some logging properties but logback xml configuration provides more powerfull features.

When a file in the classpath has one of the following names, Spring Boot will automatically load it over the default configuration:

  • logback-spring.xml
  • logback.xml
  • logback-spring.groovy
  • logback.groovy

So You can just put the code snippet below in src/main/resources/logback-spring.xml file

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="Console"
              >
        <layout >
            <Pattern>
                %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable
            </Pattern>
        </layout>
    </appender>
    <appender name="FILE" >
        <file>app.log</file>
        <append>false</append>
        <encoder>
            <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- LOG everything at INFO level -->
    <root level="info">
        <appender-ref ref="FILE" />
        <appender-ref ref="Console" />
    </root>
</configuration>

The line <append>false</append> does the job. if you wanna log more information than those avaible with the encoder pattern <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> please check logback documention https://logback.qos.ch/manual/layouts.html#logback-access

  • Related