OkHttpClient Logging Configuration with Interceptors

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.

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.