DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine
  • Overview of Android Networking Tools: Receiving, Sending, Inspecting, and Mock Servers
  • C# Applications Vulnerability Cheatsheet
  • Go Application Vulnerability Cheatsheet

Trending

  • GenAI Security Gateway: An End-to-End Architecture
  • LangChainGo vs Genkit Go: Where Genkit Shines
  • One Database, Two Models: Building AI-Friendly Java Applications With MySQL JSON Duality Views
  • Why Spark Executors Leave Cores Idle on YARN: A Packing Model for Executor Sizing

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Data
  4. OkHttpClient Logging Configuration With Interceptors

OkHttpClient Logging Configuration With Interceptors

Debugging HTTP can be complicated, but setting up the proper logging will enable you to track down issues much more quickly.

By 
Bill O'Neil
·
May. 26, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
20.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Debugging HTTP can be very tricky. You have methods, headers, cookies, sessions, SSL, redirects, status codes and many other considerations. Making sure you set up proper logging for debugging purposes will allow you to track down issues much faster. The number one debugging tool for any HTTP client should without question be cURL. Once you are comfortable with cURL you can have absolute confidence you know a request should be working. Now you just need to track down the differences from cURL and your Java HTTP client of choice. Let's take a look at logging with OkHttp.

OkHttp Interceptors

Interceptors are a powerful mechanism that can monitor, rewrite, and retry calls. Basically, interceptors are equivalent to our Undertow Middleware. An interceptor is the perfect place for request/response logging in OkHttp. They even provide an excellent HttpLoggingInterceptor as an extra library. Simply set the level you want and provide your own logging mechanism to log the provided messages. We will be using SLF4J with Logback to create a static singleton HttpLoggingInterceptor.

private static final Logger logger = LoggerFactory.getLogger(HttpClient.class);

private static final HttpLoggingInterceptor loggingInterceptor =
    new HttpLoggingInterceptor((msg) -> {
        logger.debug(msg);
    });
static {
    loggingInterceptor.setLevel(Level.BODY);
}

public static HttpLoggingInterceptor getLoggingInterceptor() {
    return loggingInterceptor;
}

 View on GitHub.

The HttpLoggingInterceptor.setLevel has a few modes. Level.NONE - no logs, Level.BASIC - Logs request and response lines, Level.HEADERS - Logs request and response lines and their respective headers, and Level.BODY - Logs request and response lines and their respective headers and bodies (if present). Use Level.BODY with caution, running it in production may unintentionally log passwords or secrets to your log files since it dumps the full request/response body.

OkHttp Interceptor Types

OkHttp has two types of interceptors that both use the exact same interface. Application interceptors are higher level and tend to deal with the final request/response. Application interceptors are great for high-level logging or adding headers/query parameters to every HTTP request. Network interceptors operate at a lower level and follow all network bounces/redirects as well as caching. Network interceptors are much more in depth and a great spot for detailed logging. For more information on interceptors check out the official Wiki.

Example Routes

To show differences between application interceptors and network interceptors types, let's add a route that redirects to an another route.

private static final HttpHandler ROUTES = new RoutingHandler()
    .get("/ping", timed("ping", (exchange) -> Exchange.body().sendText(exchange, "ok")))
    .get("/redirectToPing", (exchange) -> Exchange.redirect().temporary(exchange, "/ping"))
    .setFallbackHandler(timed("notFound", RoutingHandlers::notFoundHandler))
;

 View on GitHub.

Request Helper

Simple helper method for sending the HTTP request with a given OkHttpClient

private static void request(OkHttpClient client, String url) {
    Request request = new Request.Builder()
            .url(url)
            .get()
            .build();
    Unchecked.supplier(() -> {
        Response response = client.newCall(request).execute();
        log.debug("{} - {}", response.code(), response.body().string());
        return null;
    }).get();
}

 View on GitHub.

OkHttp Without A Logging Interceptor

We are not using any logging interceptors here, so we should expect no logging info.

log.debug("noLogging");
OkHttpClient client = new OkHttpClient.Builder().build();
request(client, "http://localhost:8080/redirectToPing");

 View on GitHub.

2017-03-08 14:18:39.984 [main] DEBUG c.s.examples.okhttp.OkHttpLogging - noLogging
2017-03-08 14:18:40.354 [main] DEBUG c.s.examples.okhttp.OkHttpLogging - 200 - ok

OkHttp With an Application Logging Interceptor

Here we are passing in the logging interceptor at the higher level application interceptor.

log.debug("interceptor");
OkHttpClient interceptorClient = new OkHttpClient.Builder()
    .addInterceptor(HttpClient.getLoggingInterceptor())
    .build();
request(interceptorClient, "http://localhost:8080/redirectToPing");

 View on GitHub.

2017-03-08 14:18:40.356 [main] DEBUG c.s.examples.okhttp.OkHttpLogging - interceptor
2017-03-08 14:18:40.367 [main] DEBUG com.stubbornjava.common.HttpClient - --> GET http://localhost:8080/redirectToPing http/1.1
2017-03-08 14:18:40.367 [main] DEBUG com.stubbornjava.common.HttpClient - --> END GET
2017-03-08 14:18:40.371 [main] DEBUG com.stubbornjava.common.HttpClient - <-- 200 OK http://localhost:8080/ping (3ms)
2017-03-08 14:18:40.371 [main] DEBUG com.stubbornjava.common.HttpClient - Connection: keep-alive
2017-03-08 14:18:40.371 [main] DEBUG com.stubbornjava.common.HttpClient - Content-Type: text/plain
2017-03-08 14:18:40.371 [main] DEBUG com.stubbornjava.common.HttpClient - Content-Length: 2
2017-03-08 14:18:40.372 [main] DEBUG com.stubbornjava.common.HttpClient - Date: Wed, 08 Mar 2017 19:18:40 GMT
2017-03-08 14:18:40.372 [main] DEBUG com.stubbornjava.common.HttpClient - 
2017-03-08 14:18:40.372 [main] DEBUG com.stubbornjava.common.HttpClient - ok
2017-03-08 14:18:40.372 [main] DEBUG com.stubbornjava.common.HttpClient - <-- END HTTP (2-byte body)
2017-03-08 14:18:40.372 [main] DEBUG c.s.examples.okhttp.OkHttpLogging - 200 - ok

Notice how we were redirected as expected but there is no indication any redirecting occurred.

OkHttp With A Network Logging Interceptor

Here we are passing in the logging interceptor at the lower level network interceptor.

log.debug("networkInterceptor");
OkHttpClient networkInterceptorClient = new OkHttpClient.Builder()
    .addNetworkInterceptor(HttpClient.getLoggingInterceptor())
    .build();
request(networkInterceptorClient, "http://localhost:8080/redirectToPing");

 View on GitHub.

2017-03-08 14:18:40.373 [main] DEBUG c.s.examples.okhttp.OkHttpLogging - networkInterceptor
2017-03-08 14:18:40.377 [main] DEBUG com.stubbornjava.common.HttpClient - --> GET http://localhost:8080/redirectToPing http/1.1
2017-03-08 14:18:40.377 [main] DEBUG com.stubbornjava.common.HttpClient - Host: localhost:8080
2017-03-08 14:18:40.377 [main] DEBUG com.stubbornjava.common.HttpClient - Connection: Keep-Alive
2017-03-08 14:18:40.377 [main] DEBUG com.stubbornjava.common.HttpClient - Accept-Encoding: gzip
2017-03-08 14:18:40.377 [main] DEBUG com.stubbornjava.common.HttpClient - User-Agent: okhttp/3.6.0
2017-03-08 14:18:40.377 [main] DEBUG com.stubbornjava.common.HttpClient - --> END GET
2017-03-08 14:18:40.379 [main] DEBUG com.stubbornjava.common.HttpClient - <-- 302 Found http://localhost:8080/redirectToPing (1ms)
2017-03-08 14:18:40.379 [main] DEBUG com.stubbornjava.common.HttpClient - Connection: keep-alive
2017-03-08 14:18:40.379 [main] DEBUG com.stubbornjava.common.HttpClient - Location: /ping
2017-03-08 14:18:40.379 [main] DEBUG com.stubbornjava.common.HttpClient - Content-Length: 0
2017-03-08 14:18:40.379 [main] DEBUG com.stubbornjava.common.HttpClient - Date: Wed, 08 Mar 2017 19:18:40 GMT
2017-03-08 14:18:40.379 [main] DEBUG com.stubbornjava.common.HttpClient - <-- END HTTP (0-byte body)
2017-03-08 14:18:40.380 [main] DEBUG com.stubbornjava.common.HttpClient - --> GET http://localhost:8080/ping http/1.1
2017-03-08 14:18:40.380 [main] DEBUG com.stubbornjava.common.HttpClient - Host: localhost:8080
2017-03-08 14:18:40.380 [main] DEBUG com.stubbornjava.common.HttpClient - Connection: Keep-Alive
2017-03-08 14:18:40.380 [main] DEBUG com.stubbornjava.common.HttpClient - Accept-Encoding: gzip
2017-03-08 14:18:40.380 [main] DEBUG com.stubbornjava.common.HttpClient - User-Agent: okhttp/3.6.0
2017-03-08 14:18:40.380 [main] DEBUG com.stubbornjava.common.HttpClient - --> END GET
2017-03-08 14:18:40.382 [main] DEBUG com.stubbornjava.common.HttpClient - <-- 200 OK http://localhost:8080/ping (1ms)
2017-03-08 14:18:40.382 [main] DEBUG com.stubbornjava.common.HttpClient - Connection: keep-alive
2017-03-08 14:18:40.382 [main] DEBUG com.stubbornjava.common.HttpClient - Content-Type: text/plain
2017-03-08 14:18:40.382 [main] DEBUG com.stubbornjava.common.HttpClient - Content-Length: 2
2017-03-08 14:18:40.382 [main] DEBUG com.stubbornjava.common.HttpClient - Date: Wed, 08 Mar 2017 19:18:40 GMT
2017-03-08 14:18:40.382 [main] DEBUG com.stubbornjava.common.HttpClient - 
2017-03-08 14:18:40.382 [main] DEBUG com.stubbornjava.common.HttpClient - ok
2017-03-08 14:18:40.383 [main] DEBUG com.stubbornjava.common.HttpClient - <-- END HTTP (2-byte body)
2017-03-08 14:18:40.383 [main] DEBUG c.s.examples.okhttp.OkHttpLogging - 200 - ok

Notice how we were redirected as expected and the log clearly shows all the network hops.

application Requests Network GitHub Log4j Cache (computing) Production (computer science) Session (web analytics) Hop (software)

Published at DZone with permission of Bill O'Neil. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine
  • Overview of Android Networking Tools: Receiving, Sending, Inspecting, and Mock Servers
  • C# Applications Vulnerability Cheatsheet
  • Go Application Vulnerability Cheatsheet

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook