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

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>

Solution 2:[2]

The spring property logging.config could be quite useful in your case. By using this property you could easily provide different configurations depending on the profile or the environment.

You still need to define the patterns by using log4j2 configuration files as allready said by Piotr P. Karwasz but you can easily switch between different setups.

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 Piotr P. Karwasz
Solution 2 Sascha Doerdelmann