Created
May 7, 2018 09:40
-
-
Save rosterloh/7348d187080ea2e8f0ba853476e393e4 to your computer and use it in GitHub Desktop.
Timber log to file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FileLoggingTree extends Timber.DebugTree { | |
private static final String LOG_TAG = FileLoggingTree.class.getSimpleName(); | |
@Override | |
protected void log(int priority, String tag, String message, Throwable t) { | |
try { | |
String path = "Log"; | |
String fileNameTimeStamp = new SimpleDateFormat("dd-MM-yyyy", | |
Locale.getDefault()).format(new Date()); | |
String logTimeStamp = new SimpleDateFormat("E MMM dd yyyy 'at' hh:mm:ss:SSS aaa", | |
Locale.getDefault()).format(new Date()); | |
String fileName = fileNameTimeStamp + ".html"; | |
// Create file | |
File file = generateFile(path, fileName); | |
// If file created or exists save logs | |
if (file != null) { | |
FileWriter writer = new FileWriter(file, true); | |
writer.append("<p style=\"background:lightgray;\"><strong " | |
+ "style=\"background:lightblue;\">  ") | |
.append(logTimeStamp) | |
.append(" :  </strong><strong>  ") | |
.append(tag) | |
.append("</strong> - ") | |
.append(message) | |
.append("</p>"); | |
writer.flush(); | |
writer.close(); | |
} | |
} catch (Exception e) { | |
Log.e(LOG_TAG,"Error while logging into file : " + e); | |
} | |
} | |
@Override | |
protected String createStackElementTag(StackTraceElement element) { | |
// Add log statements line number to the log | |
return super.createStackElementTag(element) + " - " + element.getLineNumber(); | |
} | |
/* Helper method to create file*/ | |
@Nullable | |
private static File generateFile(@NonNull String path, @NonNull String fileName) { | |
File file = null; | |
if (isExternalStorageAvailable()) { | |
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), | |
BuildConfig.APPLICATION_ID + File.separator + path); | |
boolean dirExists = true; | |
if (!root.exists()) { | |
dirExists = root.mkdirs(); | |
} | |
if (dirExists) { | |
file = new File(root, fileName); | |
} | |
} | |
return file; | |
} | |
/* Helper method to determine if external storage is available*/ | |
private static boolean isExternalStorageAvailable() { | |
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment