Sticky Code : How to Log every single URL requested in Spring

Hi everyone, in this post I just want to share simple sticky code on How to capture every single URL which requested in Spring. Okay lets rolling the ball.

Add Log4j maven dependency on your pom.xml


We will capture all URL requested by using Interceptor, so the first step you should make a class which is extend from org.springframework.web.servlet.handler.HandlerInterceptorAdapter, lets see below :

package com.estartup.sys.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class SysLogInterceptor extends HandlerInterceptorAdapter {
	private final Logger log = Logger.getLogger(getClass());
	 * This implementation always returns {@code true}.
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {"eStartup - "+request.getRequestURI()+" - Entering ... ");
		return true;
	 * This implementation is empty.
	public void postHandle(
			HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception {
	 * This implementation is empty.
	public void afterCompletion(
			HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {"eStartup - "+request.getRequestURI()+" - Exiting ... ");

as you can see in this class you will override 3 methods preHandle, postHandle, and afterCompletion.

And the second step is go to your Application Config (in this post I am using Spring Java Configuration) and register your custom interceptor.

@ComponentScan(basePackages = "com.estartup")
public class AppConfig extends WebMvcConfigurerAdapter {
	public void addInterceptors(InterceptorRegistry registry) {
		SysLogInterceptor logInterceptor = new SysLogInterceptor();		

Start your server and the result is :

Okt 08, 2016 8:00:26 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 8457 ms
[20:00:31] INFO  com.estartup.sys.util.SysLogInterceptor:20 - eStartup - /estartup/welcome - Entering ... 
[20:00:31] INFO  com.estartup.sys.util.SysLogInterceptor:41 - eStartup - /estartup/welcome - Exiting ... 

Good Luck

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>