Reputation: 17613
I'm using a custom logger to log both to Logcat
and to file (when the file is enabled).
This really helps when receiving bug reports from testers (because I have also a button inside the app to send a bug report with the logs attached).
The problem: I'm using RetroFit
, but I haven't how I can intercept it's logs and send them also to file if possible, with my own custom logger.
Is it possible?
Upvotes: 6
Views: 4464
Reputation: 1043
val logging = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
override fun log(message: String) {
LogUtils.d(TAG, message) //my logger which save logs into file
}
}
)
logging.level = HttpLoggingInterceptor.Level.BODY
val okHttpClient: OkHttpClient = OkHttpClient.Builder()
.addInterceptor(logging)
.build()
It works for me.
Upvotes: 1
Reputation: 7010
It makes sense to take as starting point OkHttp Logger Interceptor (https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor). And then redirect all output to the file. So you'll get nice looking logs with urls, headers, content.
Upvotes: 3
Reputation: 4123
In retrofit 2:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
...
HttpLoggingInterceptor.Logger fileLogger = new HttpLoggingInterceptor.Logger() {
@Override
public void log(String s) {
writeToFile(s);
}
}
Interceptor fileLoggerInterceptor = new HttpLoggingInterceptor(fileLogger);
builder.addInterceptor(fileLoggerInterceptor);
....
writeToFile
is where you actually write to the file system
For instance:
try {
FileOutputStream outputStream = mContext.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Upvotes: 12
Reputation: 4104
you can add Logger to RestAdapter when building it with
new RestAdapter.Builder()
... other methods
.setLogLevel(RestAdapter.LogLevel.FULL)
.setLog(new RestAdapter.Log() {
@Override
public void log(String message) {
// code for storing logs in file
}
})
.build();
you should adjust loglevel to whatever level it suits you
Upvotes: 5