javaspringspring-bootelastic-stackgraylog2

Retrieving the name of the method from which HTTP call was made using an Interceptor


I am using the Spring ClientHttpRequestInterceptor to capture all outgoing HTTP calls from my applications in order to log the data. In addition to the data that I am already collecting in the interceptor, I want to somehow fetch the name of the function from which the HTTP call originated. So, as an example, if a method called getStuffFromUrl is making the HTTP call using the Spring RestTemplate as follows,

public String getStuffFromUrl() {
    ...
    return restTemplate.exchange(url, HttpMethod.GET,entity, String.class).getBody();
}

when I capture this outbound HTTP call in my interceptor, I want to retrieve the name of the method getStuffFromUrl as well. How could I go about doing this?


Solution

  • If you are allowed to modify your HTTP request, one way would be to add a ad-hoc HTTP header for the method name :

    public String getStuffFromUrl() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("JavaMethod", "getStuffFromUrl");
        entity = new Entity(headers)
        ...
        return restTemplate.exchange(url, HttpMethod.GET,entity, String.class).getBody();
    }
    

    You could then get back the method name and remove the header from within the ClientHttpRequestInterceptor prior the HTTP request is actualy sent out.

    ClientHttpResponse intercept(HttpRequest request, byte[] body,
                             ClientHttpRequestExecution execution)
                      throws IOException {
    
        String javaMethodName="Unknown";
    
        List<String> javaMethodHeader = request.getHeaders().remove("JavaMethod");
        if(javaMethodHeader!=null && javaMethodHeader.size()>0) {
            javaMethodName = javaMethodHeader.get(0);
        }
    
        log.info("Calling method = "+ javaMethodName);
        execution.execute(request, body);
    }
    

    (provided code not tested)