Skip to content

Instantly share code, notes, and snippets.

@lvabarajithan
Last active May 15, 2020 14:50
Show Gist options
  • Save lvabarajithan/d27bffa7fdd43f25303726962ab8cb2e to your computer and use it in GitHub Desktop.
Save lvabarajithan/d27bffa7fdd43f25303726962ab8cb2e to your computer and use it in GitHub Desktop.
Log to file reactively in Android using RxJava and Timber
/**
* Writes logs to the file every 5 sec
* or a maximum of 10 count is reached (which ever is first)
*/
public class FileLoggingTree extends Timber.DebugTree {
private static final SimpleDateFormat LOG_DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss.SSS aa");
private static final SimpleDateFormat FILE_DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
private Relay<String> logBuffer = ReplayRelay.<String>create().toSerialized();
@SuppressLint("CheckResult")
public FileLoggingTree() {
logBuffer.buffer(5, TimeUnit.SECONDS, 10).observeOn(Schedulers.io())
.subscribe(this::_writeToFile);
}
private void _writeToFile(List<String> messages) {
try {
File logFile = _getFile();
FileWriter writer = new FileWriter(logFile, true);
for (String msg : messages) {
try {
writer.append(msg);
} catch (IOException e) {
Timber.e(e, "Unable to save log to file");
}
}
writer.flush();
writer.close();
} catch (IOException e) {
Timber.e(e, "Error writing to file, will retry");
}
}
@Override
protected void log(int priority, @Nullable String tag, @NotNull String message, @Nullable Throwable t) {
super.log(priority, tag, message, t);
String dateTime = LOG_DATE_FORMAT.format(new Date());
String logType = _getLogType(priority);
String logMessage;
if (t == null) {
logMessage = String.format("%s %s%s: %s\n", dateTime, logType, tag, message);
} else {
logMessage = String.format("%s %s%s: %s\n%s\n", dateTime, logType, tag, message, t);
}
logBuffer.accept(logMessage);
}
/**
* Get log type string from priority.
*/
private String _getLogType(int priority) {
switch (priority) {
case Log.DEBUG:
return "D/";
case Log.INFO:
return "I/";
case Log.ERROR:
return "E/";
default:
return "LOG/";
}
}
/**
* Generates a file, if doesn't exist, with current date.
*/
private File _getFile() {
File logsDir = new File(FileUtil.baseDir(), "logs");
if (!logsDir.exists()) {
logsDir.mkdirs();
}
String filename = FILE_DATE_FORMAT.format(new Date());
return FileUtil.getAsFile("logs", "logs_" + filename + ".log");
}
}
@lvabarajithan
Copy link
Author

The Relay must be serialized to make it thread safe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment