How to log IP addresses of incoming requests to a Spring Boot app in a centralized way?

Let’s say you want to track the source of hits coming to your REST services.

And you have developed them using Spring Boot.

Here is the algorithm:

STEP1: Create a Spring Handler Interceptor

STEP2: Retrieve the IP address in the prehandle method of the Handler interceptor.

2.a) Use X-Forwarded-For header extracted from HttpRequest object to find the IP address of the client

2.b) If it is not present , retrieve it from the request object itself

STEP3: Register the interceptor


Here is the Spring Interceptor :

package com.ipaddress.demo;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerInterceptor;

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

public class IPAddressInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String ipAddress = request.getHeader("X-Forward-For");

        if(ipAddress== null){

            ipAddress = request.getRemoteAddr();

        return false;

We get the IP address from the X-Forward-For header because it contains the actual ip address of the client in case if it requests through a proxy. The proxy address will not be passed through in this case in this header.

If it is not present we can retrieve it from the request object itself . Instead of printing it out as I have shown above we can log it for tracking in live environment.

Once the interceptor is created we need to register it:

package com.ipaddress.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

public class InterceptorRegistry implements WebMvcConfigurer {

    private IPAddressInterceptor ipAddressInterceptor;
    public void addInterceptors(org.springframework.web.servlet.config.annotation.InterceptorRegistry registry) {


That’s it.

Now when you hit any of the REST services in your app ,the IP address of the source of the hit will be tracked .

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s