25
Mar

slf4j MDC – the need for it.

The Java logging APIs consists of three core components:

#1. LOGGERS: captures events and pass them to appropriate APPENDER.
#2. APPENDERS: Appenders are also called HANDLERS, are responsible for RECORDING LOG EVENTS TO A DESTINATION. APPENDERS use LAYOUTS to format events, before sending them to an output.
#3. LAYOUTS: Layouts are also know as FORMATTERS. are responsible for converting and formatting the data in a Log event. Layouts determines how the data looks when it appears in log entry.

Workflow of logging:
When a Logger records an event, it forwards it to the appropriate Appender. The Appender then formats the log entry using a Layout before sending it to the console, to a file, or to another destination. In addition, Filters let you further specify whether an Appender should be used for a specific log entry. Filters aren’t required in a logging configuration, but they give you greater control over the flow of your log messages.

In a multi-threaded application, the typical log generated is difficult to read. eg. it is difficult to predict which thread log is following log capture:

17:25:19, Handling request for service
17:25:19, Requesting data from database
17:25:19, Completed request
17:25:19, Requesting data from database
17:25:19, Completed request

One of the solution to identify each log entry is to unique id specific to thread.

Another solution provided by slf4j, is MDC Mapped Diagnostic Context (MDC) to improve the application logging. Following code snippet demonstrates slf4j MDC in java:

Step 1: Create code snippet to use MDC:
—————————————-

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

public class SimpleMDC {
static public void main(String[] args) {

// You can put values in the MDC at any time. Before anything else
// we put the first name
MDC.put(“first”, “Sheetal”);

Logger logger = LoggerFactory.getLogger(SimpleMDC.class);
// We now put the last name
MDC.put(“last”, “Rastogi”);

logger.info(“your log message goes here”);

MDC.put(“first”, “Jacky”);
MDC.put(“last”, “Chan”);
logger.info(“your log message goes here”);

}

}

Step 2: configure slf4j configuration file (in resources folder)
—————————————————————–



%d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36} %X{first} %X{last} – %m%n




OUTPUT:
——-
25-03-2019 21:39:50.892 [main] INFO Package.SimpleMDC Sheetal Rastogi – your log message goes here
25-03-2019 21:39:50.893 [main] INFO Package.SimpleMDC Jacky Chan – your log message goes here