Over a million developers have joined DZone.

Contextual Logging with Java and Log4j

DZone's Guide to

Contextual Logging with Java and Log4j

Free Resource

 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);

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}