Skip to content

Instantly share code, notes, and snippets.

@s0h4m
Created September 2, 2016 18:30
Show Gist options
  • Save s0h4m/5fca09dce7eea300f294ba4273da0fe0 to your computer and use it in GitHub Desktop.
Save s0h4m/5fca09dce7eea300f294ba4273da0fe0 to your computer and use it in GitHub Desktop.
import android.content.Context;
import android.support.annotation.NonNull;
import java.lang.ref.WeakReference;
import timber.log.Timber;
/**
* Our custom TimberTree that lets us output to a file via an {@link android.app.IntentService}
* like {@link TimberService}
*/
public class FileTimberTree extends Timber.DebugTree {
/**
* we have to keep a reference to the application context so that we can launch the service which
* writes to the file
*/
private WeakReference<Context> contextWeakReference;
public FileTimberTree(final Context context) {
setContext(context);
}
/**
* Overriden so that we can add the line number to the logs!
*
* @return
*/
@Override
protected String createStackElementTag(StackTraceElement element) {
return super.createStackElementTag(element) + ":" + element.getLineNumber();
}
@Override
protected void log(int priority, String tag, String message, Throwable t) {
if (contextWeakReference != null && contextWeakReference.get() != null)
TimberService.log(contextWeakReference.get(), priority, System.currentTimeMillis() + ", " + tag, message, t);
}
public Context getContext() {
return contextWeakReference == null ? null : contextWeakReference.get();
}
public void setContext(@NonNull Context context) {
if (contextWeakReference != null) {
contextWeakReference.clear();
contextWeakReference = null;
}
this.contextWeakReference = new WeakReference<>(context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment