使HttpLoggingInterceptor不记录图像

时间:2017-09-21 09:27:14

标签: android logging retrofit okhttp

我正试图摆脱日志中的垃圾,比如

  

* $ʞxJ/

当我收到图像时

所以我试图覆盖HttpLoggingInterceptor intercept(),以检测是否存在Content-Type =>响应中的image / jpeg标头,但是HttpLoggingInterceptor是最终的,所以我无法扩展它:(

RetrofitModule中的代码:

OkHttpClient provideOkHttpClient(Context context, Application app, Preferences preferences) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.HEADERS);

        Cache cache = new Cache(app.getCacheDir(), cacheSize);

        return new OkHttpClient.Builder()
                .addNetworkInterceptor(new OkHttpInterceptor(context, preferences))
                .addInterceptor(loggingInterceptor)
                .cache(cache)
                .build();
    }

如何在项目中禁用图像记录?

2 个答案:

答案 0 :(得分:1)

所以,既然没有人有答案,我就会发明自己的自行车:

    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            if(!message.contains("�")){
                Timber.d(message);
            }
        }
    });

不确定String.contains()是否足够便宜,可以像这样使用它,但是达到了目标

答案 1 :(得分:0)

您可以使用print(np.corrcoef(A.flatten(), B.flatten())[0,1]) 类来打印没有二进制数据的日志:

OkHttpLogger

要使用它,请将实例传递给class OkHttpLogger : HttpLoggingInterceptor.Logger { override fun log(message: String) { okHttpLog(message) } private fun okHttpLog(message: String, level: Int = Log.DEBUG, t: Throwable? = null) { val maxLogLength = 4000 val tag = "OkHttp" val encoder = Charset.forName("ISO-8859-1").newEncoder() var logMessage = message if (t != null) logMessage = logMessage + '\n'.toString() + Log.getStackTraceString(t) // Split by line, then ensure each line can fit into Log's maximum length. var i = 0 val length = logMessage.length var isBinaryLogDisplayed = false var isBinaryContentType = false while (i < length) { var newline = logMessage.indexOf('\n', i) newline = if (newline != -1) newline else length do { val end = minOf(newline, i + maxLogLength) val msg = logMessage.substring(i, end).trim() if (msg.contains("Content-Type") && msg.contains("application/octet-stream")) { // use another Content-Type if need isBinaryContentType = true } val isBinaryData = !encoder.canEncode(msg) // multipart boundary if (isBinaryLogDisplayed && msg.startsWith("--")) { isBinaryContentType = false isBinaryLogDisplayed = false } // don't print binary data if (isBinaryContentType && isBinaryData && !isBinaryLogDisplayed) { Log.println(level, tag, "<BINARY DATA>") isBinaryLogDisplayed = true } if (!isBinaryLogDisplayed) { Log.println(level, tag, msg) } i = end } while (i < newline) i++ } } } 的构造函数:

HttpLoggingInterceptor