Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Logging is a vital part of software development, giving us valuable insights into our application’s behavior. In this tutorial, we’ll review an important logging feature called Parameterized logging. By leveraging parameterized logging, we can enhance the comprehensiveness and efficiency of our logs.

Simple Logging Facade for Java (SLF4J) is a widely known logging library that offers a unified abstraction for logging. It allows developers to use a single API and plug in any compatible logging framework, such as Logback, log4j, or SLF4J simple logger. SLF4J API doesn’t actually log, and we can plug whatever logging framework we want at deployment time.

2. Maven Dependencies

Before diving into logging itself, let’s configure the needed dependencies. Usually, we need to include two dependencies: slf4j-api, which will provide a unified facade, and one logger implementation that will perform logging. In our example, we’ll use Logback as a logger implementation, and here, we can go with a different approach. We need to include only a single logback-classic dependency that already uses slf4j-api.

Let’s add the logback-classic dependency to our Maven pom.xml:

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.4.8</version>
</dependency>

We can find the latest versions of separate slf4j-api and logback-classic in the Maven Central repository.

3. Logger Initialization

The first step is to initialize our logger. Depending on the project setup, this can be done manually or via Lombok. Let’s check both variants.

Manual initialization should always use Logger and LoggerFactory from the org.slf4j package:

public static final Logger log = LoggerFactory.getLogger(LoggingPlayground.class);

By using the @Slf4j annotation on the class level, Lombok will generate the same code line as the manual initialization above.

In order to be consistent and to be ready for possible migration to Lombok, we can use log names for all manually initialized loggers.

4. Parameterized Logging

Parameterized logging, from a terminology perspective, refers to the process of injecting provided parameters into the log message. In the past, older versions of libraries haven’t always provided a unified way of parameterized logging with multiple values. That’s why we can see the usage of pure string concatenations, String.format(), and other tricks. These techniques are no longer necessary, and we can use as many parameters as we want using curly braces {} inside the message.

We can log only one parameter:

log.info("App is running at {}", LocalDateTime.now());

We can log multiple parameters too, and the placeholders will be enriched in sequential order. Just remember to ensure that the number of curly braces matches the number of parameters we pass. Thankfully, most IDEs will highlight such mismatches.

Here’s an example of how to log multiple parameters:

log.info("App is running at {}, zone = {}, java version = {}, java vm = {}", LocalDateTime.now(), ZonedDateTime.now()
  .getZone(), System.getProperty("java.version"), System.getProperty("java.vm.name"));

The output of the above code will be:

15:41:48.749 [main] INFO  c.b.p.logging.LoggingPlayground - App is running at 2023-07-20T15:41:48.749435, zone = Europe/Helsinki, java version = 11.0.15, java vm = Java HotSpot(TM) 64-Bit Server VM 

One of the common approaches for the case, when the library doesn’t support multiple parameters, is to log data with Object[], but it should not be used with newer versions:

log.info("App is running at {}, zone = {}, java version = {}, java vm = {}",
  new Object[] { ZonedDateTime.now(), ZonedDateTime.now().getZone(), System.getProperty("java.version"), System.getProperty("java.vm.name") });

The output will be the same as the output with four separate objects.

5. Fluent Logging

Starting from SLF4J 2.0, Fluent Logging offers another approach that’s backward-compatible with existing frameworks. Fluent provides a builder API to build logging events step by step. Hence, we can implement parameterized logging with this feature as well. Dedicated builders are available for each log level. Each builder creation should be enclosed with a log() call to actually print the message.

For example, we can use the addArgument() method and add a parameter value to each placeholder from the message:

log.atInfo().setMessage("App is running at {}, zone = {}")
  .addArgument(LocalDateTime.now())
  .addArgument(ZonedDateTime.now().getZone())
  .log();

Our output is the same as the non-Fluent approach:

15:50:20.724 [main] INFO  c.b.p.l.FluentLoggingPlayground - App is running at 2023-07-20T15:50:20.724532900, zone = Europe/Helsinki 

Alternatively, we can use addKeyValue() and specify the parameter name along with its value:

log.atInfo().setMessage("App is running at")
  .addKeyValue("time", LocalDateTime.now())
  .addKeyValue("zone", ZonedDateTime.now().getZone())
  .setCause(exceptionCause)
  .log();

In order to use the addKeyValue() approach, our logger configuration should be able to accept it. In the case of Logback, we should update the log format to include a %kvp placeholder. If it’s not specified, then all added data will be ignored:

<appender name="out" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg %kvp%n</pattern>
    </encoder>
</appender>

With the key-value approach, our output is a bit different for the parameters’ values:

15:52:35.835 [main] INFO  c.b.p.l.FluentLoggingPlayground - App is running at time="2023-07-20T15:52:35.834338500" zone="Europe/Helsinki"

6. Parameterized Logging With Exception Logging

A question that often comes up is how to log multiple parameters with exceptions, considering that the declared methods provide the ability to pass either parameters or an exception. Starting from SLF4J 1.6, this issue is solved, and we can combine parameterized logging with exception logging.

By default, SLF4J will use the latest parameter as a candidate for Throwable. If the provided parameter is an exception, SLF4J will print the complete stack trace in the log output.

For example, for a given logline:

log.info("App is running at {}, zone = {}, java version = {}, java vm = {}", LocalDateTime.now(), ZonedDateTime.now()
  .getZone(), System.getProperty("java.version"), System.getProperty("java.vm.name"), exceptionCause);

The output will be:

15:54:43.771 [main] INFO  c.b.p.logging.LoggingPlayground - App is running at 2023-07-20T15:54:43.771587300, zone = Europe/Helsinki, java version = 11.0.15, java vm = Java HotSpot(TM) 64-Bit Server VM 
java.lang.Exception: java.lang.IllegalArgumentException: Something unprocessable
	at com.baeldung.parameterized.logging.LoggingPlayground.main(LoggingPlayground.java:30)
Caused by: java.lang.IllegalArgumentException: Something unprocessable
	... 1 common frames omitted

If we pass Throwable somewhere in between other parameters, it’ll be considered a regular object, and the stack trace won’t be printed.

Throwable can also be specified using the Fluent approach via the setCause() method:

log.atInfo()
  .setMessage("App is running at {}, zone = {}")
  .addArgument(LocalDateTime.now())
  .addArgument(ZonedDateTime.now().getZone())
  .setCause(exceptionCause)
  .log();

7. Conclusion

In this article, we’ve reviewed how to log multiple parameters with parameterized logging and explored the Fluent logging approach for even more flexibility. Additionally, we’ve explored how to combine parameterized logging with exceptions.

The complete examples are available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.