【问题标题】:OkHttp - Enable logsOkHttp - 启用日志
【发布时间】:2014-09-17 02:23:43
【问题描述】:

我使用 Retrofit 来进行 HTTP 请求和 JSON 解析,我喜欢打开调试日志的方式。日志允许查看正文请求、URL……这非常有用。由于 Retrofit 使用 OkHttp,我想知道 OkHttp 是否也有办法为每个请求启用日志。

【问题讨论】:

    标签: android web-services http okhttp


    【解决方案1】:

    还没有。但是有一个 interceptors feature 正在开发中,应该会很容易。

    【讨论】:

    【解决方案2】:

    拦截器功能目前正在审核中,但您可以通过应用 the pull request 中的代码更改来使用该功能构建您自己的 okHttp 版本。

    你可以用这样的方式实现你想要的功能

    // 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 包含在拉取请求中,如果您想查看更多信息。

    我将不得不提前警告你使用它。拦截器 API 可能会发生变化,因为它尚未被合并。不要在生产环境中使用它代码,但对于个人测试来说足够无害。

    【讨论】:

      【解决方案3】:

      使用Interceptor,您可以定义以下类:

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

      并添加它:

      OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(new LoggingInterceptor())
        .build();
      

      【讨论】:

      • 这给了我不受支持的操作
      【解决方案4】:

      现在有来自 Square(员工)的官方解决方案。 你可以试试: https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor

      【讨论】:

      • 你知道我如何记录 http2 帧吗?到目前为止我见过的所有拦截器都会记录请求。
      • 它在 Kotlin 中,而我需要 Java。
      • @JamesKPolk 如果你在java中真的需要它,源代码在那里,只需翻译它。
      【解决方案5】:

      您可以启用日志记录并与 Timber 集成以仅在调试中登录。

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

      【讨论】:

        【解决方案6】:

        为了更好的用户界面和 OkHttp 网络调用的调试,您可以使用 GANDER

        等库

        其他功能包括:

        1. 使用 Gander 的应用程序将显示一条通知,其中显示正在进行的 HTTP 活动的摘要。点击通知会启动完整的 Gander UI。应用程序可以选择性地抑制通知,并直接从它们自己的界面中启动 Gander UI。 HTTP 交互及其内容可以通过共享意图导出。

        2. 搜索 HTTP 活动以及请求和响应

        3. 主要的 Gander 活动在其自己的任务中启动,允许它与使用 Android 7.x 多窗口支持的主机应用 UI 一起显示。
        4. Gander 提供以下变体
          • 持久性:将日志保存到磁盘并且可以控制 TTL
          • 在内存数据库中:只要应用程序生命周期,日志就会在内存中。
          • 无操作:这没有任何作用。因此,如果用户只希望 Gander 在调试版本中使用,他们可以在不处理变体的情况下发布编译 NoOp,if(Build.DEBUG) ..etc

        【讨论】:

          【解决方案7】:

          为 okhttp3

          HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> Log.d(YourClass.class.getSimpleName(), "OkHttp: " + message));
          logging.setLevel(HttpLoggingInterceptor.Level.BODY);
          okHttpClient.getHttpClient().interceptors().add(logging);
          

          【讨论】:

            【解决方案8】:

            我添加一些关于 OkHttp3 的信息,因为它支持下架。

            首先,确保拥有这两个依赖项,即 OkHttp3 主包和包含记录器实现的特定包。这里我使用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>
            

            然后正确设置你的 OkHttp 客户端。

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

            主要思想是你必须向HttpLoggingInterceptor解释如何记录,所以在上面的例子中,消息只是被路由到INFO级别的Slf4j记录器。

            【讨论】:

              【解决方案9】:

              您可以使用以下方法添加日志:

                 public final OkHttpClient client = new OkHttpClient.Builder()
                     .addInterceptor(new HttpLoggingInterceptor())
                     .cache(new Cache(cacheDir, cacheSize))
                     .build();
              

              将使用默认配置:

              Logger DEFAULT = message -&gt; Platform.get().log(INFO, message, null);

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2019-08-21
                • 2018-05-19
                • 2012-08-03
                • 1970-01-01
                • 1970-01-01
                • 2011-06-16
                • 2021-10-30
                • 2017-06-10
                相关资源
                最近更新 更多