Spring boot logging into multiple files

15,662

Standard logback example, two files with different packages going to different files :

<configuration>

  <appender name="FILE1" class="ch.qos.logback.core.FileAppender">
    <file>myApp1.log</file>
    <encoder>
      <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
    </encoder>
  </appender>

  <appender name="FILE2" class="ch.qos.logback.core.FileAppender">
    <file>myApp1.log</file>
    <encoder>
      <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
    </encoder>
  </appender>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%msg%n</pattern>
    </encoder>
  </appender>

  <logger name="com.package1.foo" level="DEBUG">
    <appender-ref ref="FILE1" />
  </logger>

  <logger name="com.package2.bar" level="DEBUG">
    <appender-ref ref="FILE2" />
  </logger>

  <root level="debug">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>
Share:
15,662
user2413742
Author by

user2413742

Updated on June 04, 2022

Comments

  • user2413742
    user2413742 almost 2 years

    Is there any way I can configure spring boot logging to multiple files/console based on the configuration? i.e Some of the log statements should write into an audit file and normal log statements should go to console/normal log file.

    Below is the code I have tried on spring boot example application.

    logback-spring.xml

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

    Below is the application.properties entries

    logging.level.org.springframework.web=INFO
    logging.file=logs/spring-boot-logging.log
    

    Below the HelloController

    @RestController
    public class HelloController {
    
    Logger logger = LoggerFactory.getLogger(HelloController.class);
    
        Logger logger1 = LoggerFactory.getLogger("file");
    
        @RequestMapping("/")
        public String index() {
    
            logger.info("My Log test");
            logger1.info("My Audit test");
    
    
            return "Greetings from Spring Boot!";
        }
    
    }
    

    Can someone please help? Did anyone face similar situation?

    Thanks a lot