A Neate Blog

13 January 2022

Easily log the Request and Response of a Microprofile REST Client

Tags: Java - Microprofile - REST - Logging

Using the Microprofile REST Client makes life significantly easier when you’re having to call a REST API, if you aren’t using them already I’d definitely consider adopting them.

The biggest drawback is that it’s not always clear exactly what they’re doing, because the framework handles the majority of the work for you, it’s not as simple as just logging the entity to see what the response looks like because your logger could output the entity in a different way to the one used by the REST Client.

Luckily for us, we can easily register a LoggingFeature that will automatically log the Headers, Request and Response details for each request made. Hurrah! This is really simple and straightforward whilst being especially useful for development and debugging.

Read on to find out more!

This whole post revolves around the Jersey LoggingFeature, the JavaDocs can be found here but at a high level, you need to create a new instance of this class and in the constructor you can provide four parameters.

import org.glassfish.jersey.logging.LoggingFeature;
import java.util.logging.Level;
import java.util.logging.Logger;

// Create a new Logger instance to be passed to the LoggingFeature
Logger logger = Logger.getLogger(Example.class.getName());
/* LoggingFeature accepts four parameters
 * 1- Logger instance
 * 2- Log level (level to write the logs at)
 * 3- Verbosity (Headers only, Readable Entities, All)
 * 4- Max entity size

// Headers Only (Lowest verbosity)
LoggingFeature logFeature = new LoggingFeature(logger, Level.INFO, LoggingFeature.Verbosity.HEADERS_ONLY, 8192);

// Payload only if Textual Media (Medium verbosity)
LoggingFeature logFeature = new LoggingFeature(logger, Level.INFO, LoggingFeature.Verbosity.PAYLOAD_TEXT, 8192);

// Any payload (Highest verbosity)
LoggingFeature logFeature = new LoggingFeature(logger, Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 8192);

Now that we’ve created the logging feature, we simply need to register it with the Microprofile REST Client.

Note: In my use-case, I’m registering the feature manually and not using the Annotation RegisterProvider but I see no reason why it wouldn’t work with the annotation.

public interface ExampleRestClient { /* ... */ }

// Using the programmatic way of creating a REST Client
  .register(logFeature) // Object we created earlier

And that’s it, you’re good to go, now when the REST Client makes any requests you’ll see the details of your request and response successfully logged.

TL;DR:- You can register the Jersey LoggingFeature with the REST Client, and it will log Request and Response content out of the box. You can even alter the output to log headers only or everything.

Useful Links: