Monday 5 July 2021

Slf4j: parameterized logging

SLF4J supports parameterized logging.

 

Example

logger.info("Employee {} logged in at {}", emp1, date);

 

As shown above, you should use placeholders ({}) in the message string and pass the actual values to replace after the message string.

 

In the above example, variable emp1 is replaced at first placeholder ({}) and date is replaced at second placeholder ({}).

 

Parameterized logging feature internally calls the toString() method of the reference types.

 

Find the below working application.

 

Step 1: Define Employee model class.

 

Employee.java

package com.sample.app.model;

public class Employee {

	private int id;
	private String name;

	public Employee(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + "]";
	}

}

 

Step 2: Define ParameterizedLoggingDemo class.

 

ParameterizedLoggingDemo.java

package com.sample.app;

import java.util.Date;

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

import com.sample.app.model.Employee;

public class ParameterizedLoggingDemo {

	public static void main(String args[]) {
		Logger logger = LoggerFactory.getLogger(ParameterizedLoggingDemo.class);
		
		Employee emp1 = new Employee(123, "Krishna");
		Date date = new Date();

		logger.info("Employee {} logged in at {}", emp1, date);

	}

}

Run ‘ParameterizedLoggingDemo’ class, you will see below messages in console.


 

INFO	2021-07-05 12:10:53,846	0	com.sample.app.HelloWorld	[main]	Employee com.sample.app.model.Employee@52cc8049 logged in at Mon Jul 05 12:10:53 IST 2021

 

You can download complete working application from below link.

 

https://github.com/harikrishna553/java-libs/blob/master/slf4j/slf4j-miscellaneous/src/main/java/com/sample/app/ParameterizedLoggingDemo.java

 


 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment