Friday 25 February 2022

Logback: Parameterized logging

Logback supports parameterized logging.

 

Example

logger.info("App name: {}, version: {}", "chat server", 1.23)

 

In the above example,

a.   first {} is replaced with the string "chat server" and

b.   second {} is replaced with the number 1.23

 

Find the below working application.

 

ParameterizedLoggingDemo.java

package com.sample.app;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ParameterizedLoggingDemo {

	public static void main(String[] args) {

		Logger logger = LoggerFactory.getLogger(HelloWorld.class);
		logger.info("App name: {}, version: {}", "chat server", 1.23);

	}
}

 

Output

14:07:34.036 [main] INFO com.sample.app.HelloWorld - App name: chat server, version: 1.23

How Parameterized logging improve the performance?

Let me explain with below example.

String appName = "Chat server";
double version = 1.23;
logger.info("App name: ", + appName + ", version: " + version);

In the above example, logging involves the cost of constructing the message by concatenating the values. This processing will happen even though you turned off the logging or set to logging level above INFO.

 

One way to avoid this message construction is surrounding  the log statement by a condition.

if (logger.isInfoEnabled()) {
	String appName = "Chat server";
	double version = 1.23;

	logger.info("App name: ", + appName + ", version: " + version);
}

But the condition will be evaluated always and code is redundant while logging.

 

How parameterized logging addressed above problem?

logger.info("App name: {}, version: {}", "chat server", 1.23);

 

In the above snippet , logger first evaluate whether logging level is valid or not. When the logging level is valid, then logger format the message and replace the '{}' pair with the respective values.



 

Previous                                                 Next                                                 Home

No comments:

Post a Comment