skip to content

In a Retrofit app, how do you log HTTP traffic with OkHttp's HttpLoggingInterceptor, and how do you keep it out of release builds?

level: juniorimportance: should knowfreq 62%

answer

  1. Retrofit delegates to its client
  2. separate logging artifact
  3. four levels, default logs nothing
  4. debug flag picks the level
  5. redactHeader for Authorization

basics

~20 s

Add an HttpLoggingInterceptor to the OkHttpClient passed to Retrofit.Builder.client(), pick BASIC, HEADERS or BODY in debug builds, keep NONE (its default) in release, and call redactHeader("Authorization") so the bearer token is masked in the log.

solid answer

~40 s

Retrofit has no logging switch of its own: every call runs on the `OkHttpClient` given to `Retrofit.Builder.client()`, so logging is an OkHttp interceptor from the `com.squareup.okhttp3:logging-interceptor` artifact. I create `HttpLoggingInterceptor()`, set `level` to `BASIC` (request and response lines), `HEADERS` (plus headers) or `BODY` (plus bodies), and add it with `addInterceptor`, after the auth-header interceptor so it shows the header that interceptor added. Its default `level` is `NONE`. Because `HEADERS` and `BODY` can leak bearer tokens, cookies and personal data into logcat, the level comes from a debug-build flag and release ships `NONE`, or never adds the interceptor. `redactHeader("Authorization")` prints `██` in place of the value without changing the request, though bodies are never redacted. `BODY` also reads each whole response body into memory before passing it on, another reason it stays out of release.

code

kotlin · 20 lines
kotlin
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit

fun buildRetrofit(authInterceptor: Interceptor, debug: Boolean): Retrofit {
    val logging = HttpLoggingInterceptor().apply {
        level = if (debug) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
        redactHeader("Authorization")
        redactHeader("Cookie")
    }
    val client = OkHttpClient.Builder()
        .addInterceptor(authInterceptor) // runs first and attaches the bearer token
        .addInterceptor(logging)         // runs second, so it sees (and redacts) that header
        .build()
    return Retrofit.Builder()
        .baseUrl("https://api.example.com/")
        .client(client)
        .build()
}

go deeper

for a junior

Recall that logging comes from OkHttp's HttpLoggingInterceptor added to the client you give Retrofit, the four levels, and that NONE is the default.

for a middle

Explain why the logger's position relative to the auth interceptor changes what it prints, and how redactHeader hides a value without altering the request.

for a senior

Show a release policy that cannot leak tokens or personal data, and know that BODY buffers whole responses, which hurts large downloads.

for a principal

Decide what the team may log in each build type, who can read those logs, and how that policy is enforced rather than left to each developer.

## Where logging lives in a Retrofit stack Retrofit 3 has no logging setting. `Retrofit.Builder.client()` takes an `OkHttpClient`, and every call a service method makes is executed by that client. Logging the traffic therefore means adding an OkHttp **interceptor**: `HttpLoggingInterceptor`, shipped in its own artifact, `com.squareup.okhttp3:logging-interceptor`. If you never call `client()` (or `callFactory()`), Retrofit builds a plain `OkHttpClient()` with no interceptors, and nothing is logged. The interceptor writes each line through a `Logger`. `Logger.DEFAULT` sends lines to the platform log, which on Android is logcat at info level. Pass your own `Logger` to the constructor to route lines somewhere else, such as the app's logging facade. ## The four levels `level` is a mutable, `@Volatile` property, so it can be changed while the app runs. Its default is `Level.NONE`. | Level | What it prints | |---|---| | `NONE` | nothing; the request passes straight through | | `BASIC` | the request line and the response line, with body sizes and timing | | `HEADERS` | the two lines plus every request and response header | | `BODY` | lines, headers and bodies | A few details of `BODY` matter in practice: - To print a response body it **reads the whole body into memory** first and only then hands the response on, so a large download is fully buffered even when the service method meant to stream it. - A body that looks binary is summarised as an omitted binary body instead of being printed, but it has still been buffered. - Request bodies that are one-shot or duplex, and bodies with an unrecognised `Content-Encoding`, are left out; gzip bodies are decompressed for display. - A `text/event-stream` response is noted as streaming and is not buffered. ## Reading the output Each exchange produces a recognisable block, which helps when a tester pastes a log into a bug report: - `--> POST https://api.example.com/path` opens the request; the protocol, such as `http/1.1`, is appended only when the logger runs as a network interceptor. At `HEADERS` and `BODY` the headers, the body and a closing `--> END POST` follow. - `<-- 200 OK https://... (22ms)` opens the response, with the elapsed time; at `BASIC` the body size is added to that line. - `<-- END HTTP` closes it, with the body size at `BODY`. - `<-- HTTP FAILED: ...` replaces the response block when the call throws, for example on a timeout, so transport failures are visible too. ## Keeping it out of release builds The logging interceptor's own README warns that `HEADERS` and `BODY` can leak `Authorization` and `Cookie` headers and the contents of bodies. On a phone, logcat can be read over adb and is often attached to bug reports. The usual policy has three parts: 1. Choose the level from a debug-build flag the build supplies: `BODY` or `HEADERS` in debug, `NONE` in release. 2. Or construct and add the interceptor only in debug builds, so release code never creates it. 3. Keep redaction on in debug too, because debug builds are handed to testers and their logs get shared. Whichever you choose, a release build must not print tokens or personal data. ## Redaction - `redactHeader(name)` replaces the logged value of that header with `██`. Header names match case-insensitively. Only the log line changes: the server still receives the real header. - `redactQueryParams(vararg names)` does the same for query-parameter values in the logged URL. It arrived in OkHttp 5. Retrofit 3.0.0 depends on OkHttp 4.12, so this method exists only once the app resolves OkHttp 5 or later. - Neither method touches **bodies**. At `BODY`, a token-refresh response prints the new access and refresh tokens in full, which is one more reason to keep `BODY` to debug builds. ## The slot it sits in Interceptors added with `addInterceptor` run in the order they were added, each passing its request to the next. A logger therefore prints the request **as it looks at its own position** in that list: - Added **after** the auth-header interceptor, it prints the `Authorization` header, which is why that header should be redacted. - Added **before** it, it prints the request without the header, which misleads anyone debugging a 401. - Added with `addNetworkInterceptor` instead, it also prints the headers OkHttp adds itself and every redirect or authentication retry. How the two kinds of interceptor differ is OkHttp's own subject; for a Retrofit app, the application slot after the auth interceptor is the common choice. ## Common mistakes - Looking for a Retrofit builder option that turns logging on. - Leaving `BODY` on in a release build. - Believing `redactHeader` removes the header from the request. - Logging large file downloads at `BODY` and then chasing a memory spike. - Adding the logger before the auth interceptor and concluding that the token was never attached.

  • Why might HttpLoggingInterceptor's output show no Authorization header even though your auth interceptor adds one?
    Application interceptors run in the order they were added, and each sees the request as it is at its position. If the logger was added before the auth-header interceptor, it logs the request before the header exists. Add the logger after it, and redact `Authorization`, so the log reflects what is actually sent.
  • Can you raise HttpLoggingInterceptor's level without rebuilding the OkHttpClient?
    Yes. `level` is a mutable `@Volatile` property, so a debug menu can switch it from `NONE` to `BODY` at runtime and the next call picks it up. The client and the Retrofit instance stay the same; only the interceptor's field changes.

  • Retrofit.Builder has its own log-level option for requests.
  • A new HttpLoggingInterceptor logs bodies by default.
  • BODY logging is fine in release because logcat is private to the app.
  • redactHeader strips the Authorization header from the request sent to the server.
  • Where the logger sits in the interceptor list cannot change what it prints.

Assumes Retrofit 3.0.0 on OkHttp 4.12 for the logging setup, and OkHttp 5 for redactQueryParams, which 4.x does not have.