Skip to content

Instrumenting Jersey Clients

WolfgangTheilmann edited this page Mar 31, 2016 · 3 revisions

Introduction

Jersey Container instrumentation is implemented as a combination of a client request filter and a client response filter as defined in the Java API for RESTful Services (JAX-RS), Version 2.0

Note:The code snippets below are taken from the sample application. You may want to consult the Sample.java file to get the full picture.

Enabling the Feature

In order to make this feature available in your application, you need to add the corresponding library to your Maven dependencies in your application's pom.xml like this, assuming that you've also defined a property cf-logging-version that refers to the latest version of this feature:

<!-- We're using the Servlet Filter instrumentation -->
<dependency>
   <groupId>com.sap.hcp.cf.logging</groupId>
   <artifactId>cf-java-logging-support-jersey</artifactId>
   <version>${cf-logging-version}</version>
</dependency>

Enabling the Request/Response Filters

There is no automatic way to register these filters. Instead, they need to be part of the ClientConfig instance that is used to create an outbound call. Here's how we do it in our sample application:

@Path("/")
public class Sample {

  private ClientConfig clientConfig = new ClientConfig().register(RequestMetricsClientRequestFilter.class).register(RequestMetricsClientResponseFilter.class);

Later on, whenever we make an outbound call, that config is passed to ClientBuilder to create an outgoing request:

    Invocation.Builder forwReq = ClientBuilder.newClient(clientConfig).target(targetUri.toString()).request();

Propagating Correlation IDs

When the outbound call is made, it will most likely happen in a different thread. If so, the correlation id that may have been stored in the thread-local MDC will not be available and thus will not be forwarded to the service that is called. In order to propagate the correlation id, you should use the utility class ClientRequestUtils to add the id to the request headers before making the outbound call:

    forwReq = ClientRequestUtils.propagate(forwReq, headers);
    return Response.status(200).entity(forwReq.get(String.class)).build();