HttpLoggingInterceptor没有显示任何日志

3

我尝试使用Retrofit2的HttpLoggingInterceptor,但一直没有结果,任何请求/响应都没有显示任何日志。

以下是我使用的库版本:

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.6.0'

我需要生成API实例的代码如下:

public class ApiGenerator {

    private static final String BASE_URL = "http://api.openweathermap.org/data/2.5/";
    private static final String API_KEY = "de4d4a35830d98e785a1cbb06725457f";

    private ApiGenerator() {}

    public static WeatherApi createWeatherApi() {
        return createRetrofit().create(WeatherApi.class);
    }

    private static Retrofit createRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(createClient())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    private static OkHttpClient createClient() {

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        return new OkHttpClient.Builder().addInterceptor(chain -> {
            Request request = chain.request();
            HttpUrl url = request.url().newBuilder()
                    .addQueryParameter("APPID", API_KEY)
                    .build();
            request.newBuilder().url(url).build();
            return chain.proceed(request);
        })
                .addInterceptor(logging)
                .build();
    }
}
2个回答

6

你的示例正在使用默认日志记录器,可能没有进行配置。更好的解决方案是使用您选择的日志框架传递自定义日志记录器。 使用SLF4J和Logback的示例

private static final Logger log = LoggerFactory.getLogger(HttpClient.class);

private static final HttpLoggingInterceptor loggingInterceptor =
    new HttpLoggingInterceptor((msg) -> {
        log.debug(msg);
    });
static {
    loggingInterceptor.setLevel(Level.BODY);
}

public static HttpLoggingInterceptor getLoggingInterceptor() {
    return loggingInterceptor;
}

-1

Bill的答案的Kotlin版本

val log: Logger = LoggerFactory.getLogger("HttpLogging")
val okHttpLoggingInterceptor = HttpLoggingInterceptor { log.debug(it) }.setLevel(BODY)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接