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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  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.

Bill O'Neil user avatar by
Bill O'Neil
·
May. 26, 17 · Tutorial
Like (4)
Save
Tweet
Share
15.80K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Popular on DZone

  • Shift-Left: A Developer's Pipe(line) Dream?
  • Best Navicat Alternative for Windows
  • Integrate AWS Secrets Manager in Spring Boot Application
  • Building the Next-Generation Data Lakehouse: 10X Performance

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: