Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit -> Log to file

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?

like image 776
neteinstein Avatar asked Nov 18 '14 17:11

neteinstein


1 Answers

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();
}
like image 156
Joao Sousa Avatar answered Sep 22 '22 10:09

Joao Sousa