Over a million developers have joined DZone.

Contextual Logging with Java and Log4j


 Contextual Logging in Log4j. 

Steps to do the Contextual Logging

Configuring one time which is very efficient.

log4j.properties -- text highlighted in green specifies contextual information

1) log4j.appender.stdout.layout.ConversionPattern=%-5p %-23d{MM-dd-yyyy HH:mm:ss:S} [%t] %X{clientRequestIP} %X{timestamp} %X{session} %X{loggedinuserid} %X{loggedinusername} %X{httpmethod}  %X{requesturl} %c:%L %m%n

2) Code Snippet
Put this code in Filter class. This will be invoked once per request and attach unique timestamp which will be prepended for each controller, service, dao, adapter methods

		import org.apache.log4j.MDC;
	    	. . . . . .
		. . . . . .
		final long timestamp = (new Date()).getTime();
		MDC.put("timestamp", timestamp);
		MDC.put("httpmethod", httpmethod);
		MDC.put("session", sessionid);
		MDC.put("requesturl", requestUrl);
		MDC.put("loggedinusername", username);

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}