Android改造日志不显示

Android Retrofit log does not show

Retrofit 不打印日志。日志级别设置为详细。也尝试了 HttpLoggingInterceptor。

使用这些 gradles

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

代码

OkHttpClient httpClient = new OkHttpClient();
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.newBuilder().connectTimeout(6, TimeUnit.MINUTES)
                .readTimeout(6, TimeUnit.MINUTES)
                .writeTimeout(6, TimeUnit.MINUTES)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request original = chain.request();
                        Request.Builder requestBuilder = original.newBuilder()
                                .header("Content-Type", "application/json")
                                .header("Authorization", "aDRF@F#JG_a34-n3d")
                                .method(original.method(), original.body());
                        Request request = requestBuilder.build();
                        return chain.proceed(request);
                    }
                })
    .addInterceptor(httpLoggingInterceptor);


return httpClient;

事实上,我不知道您为什么看不到日志,但这是我的部分代码,运行良好:

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
httpClientBuilder.addInterceptor(logging);

String creditentials = username + ":" + password;
_base64 = "Basic " + Base64.encodeToString(creditentials.getBytes(), Base64.NO_WRAP);

Interceptor authorization = chain -> {
    Request newRequest = chain.request().newBuilder()
            .addHeader("Authorization", _base64)
            .addHeader("Accept", "application/json")
            .build();
    return chain.proceed(newRequest);
};

httpClientBuilder.addInterceptor(authorization);

_retrofit = new Retrofit.Builder()
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl(API_URL)
        .client(httpClientBuilder.build())
        .build();

在某些情况下,您需要在某些物理 android 设备上允许扩展日志。 这可以在 android phone 设置中的开发人员菜单中完成。

当我的模拟器的 Developer options 中的 Log buffer 设置为 Off 时,我无法看到 OkHttp 网络日志,所以在我更改为任何其他值(例如 16m)并再次尝试后,它可以正确显示日志.

在某些设备(模拟器或真实 Android 设备)上,默认情况下禁用日志记录。您需要启用此选项才能查看日志。 用魅族 M3s 试过。

  1. 转到开发人员选项

  2. 查找性能优化.

  3. 查找高级日志记录

  4. 全部允许。

请注意,对于不同的设备,步骤可能略有不同。

在我的例子中,我忘记调用 setLevel(HttpLoggingInterceptor.Level.BASIC),默认情况下它被隐式设置为 NONE