DEV Community

Cover image for OkTrace: See Exactly What Each OkHttp Interceptor Changes
Dheerendra Chaturvedi
Dheerendra Chaturvedi

Posted on

OkTrace: See Exactly What Each OkHttp Interceptor Changes

If you've ever chased a mysterious 401 through a stack of five OkHttp interceptors, you know the pain: HttpLoggingInterceptor shows you the final request โ€” but not which interceptor added, removed, or overwrote that header.

OkTrace fixes exactly that. It logs a diff at every step of the interceptor chain.

What you get

  • ๐Ÿ” Per-interceptor diffs โ€” headers added / removed / changed, URL rewrites, method changes, body changes
  • โฑ๏ธ Timings for each step plus total duration
  • ๐Ÿ“ฆ Programmatic access to traces via OkTrace.store.entries
  • โš™๏ธ Configurable: OkTrace.enabled, OkTrace.logTag, TraceStore.maxEntries

Diff legend:

Symbol Meaning
+ header added
- header removed
~ header / URL / body changed
[pass-through] interceptor changed nothing

Example output

[1] AuthInterceptor      ยท 2ms
    + Authorization: Bearer โ€ขโ€ขโ€ขโ€ข
[2] HeaderInterceptor    ยท 0ms
    ~ User-Agent: okhttp โ†’ app/2.1
    - X-Debug
[3] RetryInterceptor     ยท 0ms
    [pass-through]
โ† 200 OK ยท total 184ms
Enter fullscreen mode Exit fullscreen mode

Now you know instantly that HeaderInterceptor is the one stripping X-Debug.

Installation

Add JitPack in settings.gradle.kts:

maven { url = uri("https://jitpack.io") }
Enter fullscreen mode Exit fullscreen mode

Then the dependency:

implementation("com.github.NarendraKumar-2259:OkTrace:1.0.0")
Enter fullscreen mode Exit fullscreen mode

Usage

Put OkTrace.interceptor() first, then wrap each of your interceptors with observe():

val client = OkHttpClient.Builder()
    .addInterceptor(OkTrace.interceptor())
    .addInterceptor(OkTrace.observe(AuthInterceptor()))
    .addInterceptor(OkTrace.observe(HeaderInterceptor()))
    .build()
Enter fullscreen mode Exit fullscreen mode

Enable it only for debug builds:

OkTrace.enabled = BuildConfig.DEBUG
Enter fullscreen mode Exit fullscreen mode

โš ๏ธ OkTrace logs request data (including auth headers), so keep it debug-only โ€” never ship it enabled in production.

Try it & contribute

OkTrace is open source under Apache 2.0. If it saves you a debugging session, drop a โญ on the repo, open an issue, or send a PR:

๐Ÿ‘‰ https://github.com/NarendraKumar-2259/OkTrace

What's the nastiest interceptor bug you've hunted down? Share it in the comments ๐Ÿ‘‡

Top comments (0)