Junior — Middle
How can logging be implemented when using Retrofit and OkHttp for network requests?
sobes.tech AI
Answer from AI
To log network requests when using Retrofit and OkHttp, the HttpLoggingInterceptor from the OkHttp library is commonly used. This interceptor allows logging details of requests and responses, including headers, body, and status.
Example setup:
val loggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY // Log request and response bodies
}
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build()
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
Logging levels:
- NONE — no logs
- BASIC — logs only basic data (method, URL, response code)
- HEADERS — logs headers
- BODY — logs everything, including request and response bodies
This approach helps debug network interactions and quickly identify errors.