OkHttp - Enable logs
Asked Answered
L

10

29

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.

Lorilee answered 25/7, 2014 at 9:17 Comment(0)
T
17

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.

Thigpen answered 23/8, 2014 at 8:35 Comment(0)
I
36

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();
International answered 3/6, 2015 at 16:20 Comment(1)
the gives me unsupported actionGrubb
T
17

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.

Thigpen answered 23/8, 2014 at 8:35 Comment(0)
C
7

None yet. But there's an interceptors feature under development that should make it easy.

Creolized answered 25/7, 2014 at 12:19 Comment(1)
The feature is already implemented: github.com/square/okhttp/wiki/InterceptorsBecket
P
5

There's an official solution from Square (employee) now. You can try: https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor

Purpurin answered 22/4, 2017 at 15:29 Comment(3)
do you know how i can log http2 frames? all the interceptors I've seen so far log requests.Dramshop
It's in Kotlin, whereas I need Java.Xl
@JamesKPolk if you really need it in java, source code is there, just translate it.Purpurin
M
4

for okhttp3

HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> Log.d(YourClass.class.getSimpleName(), "OkHttp: " + message));
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient.getHttpClient().interceptors().add(logging);
Maundy answered 13/3, 2020 at 13:32 Comment(0)
M
3

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();
Mesial answered 13/12, 2018 at 22:42 Comment(0)
U
3

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.

Uncomfortable answered 5/6, 2020 at 11:19 Comment(0)
P
1

For better ui and debugging of OkHttp Network calls you can use libraries like GANDER

Others features include :

  1. 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.

  2. Search HTTP Activity and also request and response

  3. 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.
  4. 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
Payoff answered 8/6, 2019 at 13:12 Comment(0)
S
0

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);

Snippet answered 14/10, 2021 at 9:31 Comment(0)
D
0

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.

Doble answered 11/1 at 18:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.