I used Retrofit in order to make HTTP requests and JSON parsing and I loved the way to turn on debug logs. Logs allow to see body requests, URL... which is very useful. As Retrofit use OkHttp, I'm wondering if OkHttp also have a way to enable logs for each requests made.
The interceptors feature is currently in review, but you can build your own version of okHttp with the feature by applying the code changes in the pull request.
You can implement the functionality you want with something like this
// Create an interceptor which catches requests and logs the info you want
RequestInterceptor logRequests= new RequestInterceptor() {
public Request execute(Request request) {
Log.i("REQUEST INFO", request.toString());
return request; // return the request unaltered
}
};
OkHttpClient client = new OkHttpClient();
List<RequestInterceptor> requestInterceptors = client.requestInterceptors();
requestInterceptros.add(logRequests);
A test is included within the pull request if you want to see more.
I'm going to have to warn you ahead of time about using this. There may be changes to the interceptor API since it has yet to be merged in. Don't use it with production code, but it's innocuous enough for personal testing.
Using an Interceptor
, you can define the following class:
class LoggingInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Log.d("OkHttp", String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Log.d("OkHttp", String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}
And add it:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
The interceptors feature is currently in review, but you can build your own version of okHttp with the feature by applying the code changes in the pull request.
You can implement the functionality you want with something like this
// Create an interceptor which catches requests and logs the info you want
RequestInterceptor logRequests= new RequestInterceptor() {
public Request execute(Request request) {
Log.i("REQUEST INFO", request.toString());
return request; // return the request unaltered
}
};
OkHttpClient client = new OkHttpClient();
List<RequestInterceptor> requestInterceptors = client.requestInterceptors();
requestInterceptros.add(logRequests);
A test is included within the pull request if you want to see more.
I'm going to have to warn you ahead of time about using this. There may be changes to the interceptor API since it has yet to be merged in. Don't use it with production code, but it's innocuous enough for personal testing.
None yet. But there's an interceptors feature under development that should make it easy.
There's an official solution from Square (employee) now. You can try: https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor
for okhttp3
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> Log.d(YourClass.class.getSimpleName(), "OkHttp: " + message));
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient.getHttpClient().interceptors().add(logging);
you can enble logging and integerate with Timber to log only in debug.
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Timber.tag("OkHttp: ");
Timber.i(message);
}
}).setLevel(HttpLoggingInterceptor.Level.BODY);
client = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.build();
I add some info regarding OkHttp3, because it supports logging out of the shelf.
First, be sure to have both these dependencies, the OkHttp3 main package and the specific package containing the logger implementations. Here I use 3.14.6
.
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.6</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>logging-interceptor</artifactId>
<version>3.14.6</version>
</dependency>
Then set up your OkHttp client properly.
...
import okhttp3.logging.HttpLoggingInterceptor;
...
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> logger.info(message));
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(interceptor)
.build();
The main idea is that you have to explain to the HttpLoggingInterceptor
how to log, so in the above example the message is just routed to an Slf4j logger at INFO
level.
For better ui and debugging of OkHttp Network calls you can use libraries like GANDER
Others features include :
Apps using Gander will display a notification showing a summary of ongoing HTTP activity. Tapping on the notification launches the full Gander UI. Apps can optionally suppress the notification, and launch the Gander UI directly from within their own interface. HTTP interactions and their contents can be exported via a share intent.
Search HTTP Activity and also request and response
- The main Gander activity is launched in its own task, allowing it to be displayed alongside the host app UI using Android 7.x multi-window support.
- Gander Provides following variants
- Persistence : Saves logs to disk and TTL can be controlled
- In Memory Database : Logs will be in memory as long as the app lifecycle.
- No Op : This does nothing. So if users want Gander only in debug builds they can releaseCompile NoOp without dealing with variants, if(Build.DEBUG) ..etc
You can add logs by using:
public final OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor())
.cache(new Cache(cacheDir, cacheSize))
.build();
Which will use default config:
Logger DEFAULT = message -> Platform.get().log(INFO, message, null);
Here is the solution in Kotlin:
class LoggingInterceptor : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request: Request = chain.request()
val t1 = System.nanoTime()
Log.d("OkHttp", String.format("Sending request %s on %s%n%s",
request.url, chain.connection(), request.headers))
val response: Response = chain.proceed(request)
val t2 = System.nanoTime()
Log.d("OkHttp", String.format("Received response for %s in %.1fms%n%s",
response.request.url, (t2 - t1) / 1e6, response.headers
))
return response
}
}
// Add the LoggingInterceptor to OkHttpClient
val client: OkHttpClient = OkHttpClient.Builder()
.addInterceptor(LoggingInterceptor())
.build()
}
This code uses the LoggingInterceptor
class to log information about outgoing requests and incoming responses. The OkHttpClient
instance is then configured with this interceptor, allowing you to use it for making network requests with OkHttp
while logging details for debugging or monitoring purposes.
© 2022 - 2024 — McMap. All rights reserved.