I'm trying to get rid of trash in logs, like
*�$ʞx���J/
when i recieve an image
So i tried to override HttpLoggingInterceptor intercept(), to detect is there a Content-Type => image/jpeg header in responce, but HttpLoggingInterceptor is final so i cant extend it :(
Code in 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();
}
How can i disable image-logging in my project?
So, since no one have an answer iv'e invent my own bicycle:
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
if(!message.contains("�")){
Timber.d(message);
}
}
});
Not really sure if String.contains() cheap enough for use it like this, but goal is reached
You can use OkHttpLogger
class to print logs without binary data:
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++
}
}
}
To use it pass an instance to HttpLoggingInterceptor
's constructor:
val httpLoggingInterceptor = HttpLoggingInterceptor(OkHttpLogger()).apply {
level = HttpLoggingInterceptor.Level.BODY
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With