Search code examples
springspring-bootloggingyamllog4j

Spring Boot multiple log4j appenders in application.yml file


I need 2 different logging patterns in my SpringBoot application.

let's say:

first_pattern  -- for root logger (INFO level)
second_pattern -- for packages com.stackoverflow.engine.core (DEBUG level)

Both packages must log to stdout.

Is it possible to configure that in application.yml ?
(not in XML or property files but in YML)

Many Thanks!


Solution

  • No, you can't obtain such a configuration using Spring configuration alone. Spring Boot supports only a couple of configuration options common to all logging frameworks (cf. documentation).

    If you want a more complex configuration, you need to use the native configuration format of the specific logging framework you are using.

    If you are using Log4j 2.x, you can extend the default Spring configuration and save it as log4j2-spring.yml in your classpath:

    Configuration:
      packages: org.springframework.boot.logging.log4j2
      properties:
        property:
          - name: LOG_EXCEPTION_CONVERSION_WORD
            value: "%xwEx"
          - name: LOG_LEVEL_PATTERN
            value: "%5p"
          - name: LOG_DATEFORMAT_PATTERN
            value: "yyyy-MM-dd HH:mm:ss.SSS"
          - name: CONSOLE_LOG_PATTERN
            value: "%clr{%d{${sys:LOG_DATEFORMAT_PATTERN}}}{faint} %clr{${sys:LOG_LEVEL_PATTERN}} %clr{%pid}{magenta} %clr{---}{faint} %clr{[%15.15t]}{faint} %clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}"
          - name: FILE_LOG_PATTERN
            value: "%d{${LOG_DATEFORMAT_PATTERN}} ${LOG_LEVEL_PATTERN} %pid --- [%t] %-40.40c{1.} : %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}"
    
      appenders:
        appender:
          - name: Console
            type: Console
            PatternLayout:
              pattern: "${sys:CONSOLE_LOG_PATTERN}"
          - name: Console2
            type: Console
            PatternLayout:
              pattern: "Pattern2 %d %p %c{1.} [%t] %m%n"
    
      loggers:
        logger:
          - name: com.stackoverflow.engine.core
            level: DEBUG
            additivity: false
            AppenderRef:
              - ref: Console2
        root:
          level: INFO
          AppenderRef:
            - ref: Console
    

    Remark: to use the YAML format, you need to add jackson-datatype-yaml to your dependencies. If you use Maven add:

    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-yaml</artifactId>
        <!-- version managed by Spring Boot -->
    </dependency>