Samuel Masue

Yet another tech blog! Let's talk about Alfresco, Java, Linux, ...

Spring boot: use YAML to configure log4j2

Let’s see how to use YAML to configure log4j2 on a Spring boot application.

Maven

Basically, you need to exclude from your pom.xml the dependency tospring-boot-starter-logging and add instead spring-boot-starter-log4j2. Then to work with YAML you have to add the dependency to jackson-dataformat-yaml.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-yaml</artifactId>
  <version>2.6.0-rc4</version>
</dependency>

If your project does not depend on spring-boot-starter-web because it is not web. Then you will need to add this dependency com.fasterxml.jackson.core:jackson-databind.

YAML

The configuration goes in a file named log4j2.yml located in the folder resources. Hereunder is an example of configuration. There are two appenders, console and rolling file then, there is the root logger and two specialized loggers for two classes.

Configutation:
  status: warn

  Appenders:
    Console:
      name: CONSOLE
      target: SYSTEM_OUT
      PatternLayout:
        Pattern: "%d{ISO8601} %-5p [%c{3}] [%t] %m%n"
    RollingFile:
      - name: APPLICATION
        fileName: ../logs/my-app.log
        filePattern: "../logs/$${date:yyyy-MM}/my-app-%d{yyyy-MM-dd}-%i.log.gz"
        PatternLayout:
          Pattern: "%d{ISO8601} %-5p [%c{3}] [%t] %m%n"
        policies:
          TimeBasedTriggeringPolicy:
            interval: 1
            modulate: true

  Loggers:
      Root:
        level: info
        AppenderRef:
          - ref: CONSOLE
          - ref: APPLICATION
      Logger:
        - name: com.myco.myapp.Foo
          additivity: false
          level: info
          AppenderRef:
            - ref: CONSOLE
            - ref: APPLICATION
        - name: com.myco.myapp.Bar
          additivity: false
          level: debug
          AppenderRef:
            - ref: CONSOLE
            - ref: APPLICATION

Class

Examples using slf4j:

  • In Groovy.
@Slf4j
class Foo {
  // some code
  log.debug("Test debug: $myvar")
}
  • In Java.
public class Bar{
  private Logger logger = LoggerFactory.getLogger(Bar.class);

  // some code
  logger.debug("Test debug: {}", myvar);
}
comments powered by Disqus