Created
September 15, 2021 14:06
-
-
Save renatojobal/cd4bcd35527fc69ad2db9f2765be1694 to your computer and use it in GitHub Desktop.
Function to save log files
This file contains 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
/** | |
* If the date is the same as the file, continue adding logs, but if the file has | |
* a past date, update that file to Firebase storage and delete that file. | |
*/ | |
fun appendLog(context: Context, targetText: String) { | |
Timber.d("Saving a new log") | |
// Get flog files in local storage | |
val date = Date() | |
val stringDate: String = SimpleDateFormat("yyyy_MM_dd", Locale.US).format(date) | |
val logsFiles: Array<out File>? = File("${context.filesDir}/$logsDir").listFiles() | |
Timber.d("Logs files: ${logsFiles?.size}") | |
var fileForTodayExists = false // flag used to create a log file or not | |
// Check out hte log files | |
logsFiles?.forEach { file -> | |
Timber.d("File log name: ${file.name}") | |
if (file.name == "$stringDate$suffixName") { // Log file for today fount | |
Timber.i("File for this day exists") | |
fileForTodayExists = true | |
} else { // Update this past file to Firebase storage and delete it (In background) | |
Timber.i("There is a file for a previous day") | |
CoroutineScope(Dispatchers.IO).launch { | |
Timber.i("Sending previous file to firebase storage") | |
val logReference = FirebaseStorage | |
.getInstance() | |
.reference | |
.child("logs/${file.name}") | |
val uriFile = Uri.fromFile(file) | |
val uploadTask = logReference.putFile(uriFile) | |
uploadTask.addOnFailureListener { e -> | |
Timber.e(e) | |
}.addOnSuccessListener { _ -> | |
// Delete the file form local storage | |
Timber.i("Successfully sent file. Delete file from local storage") | |
file.delete() | |
} | |
} | |
} | |
} | |
// If the file does not exist, create it | |
if (!fileForTodayExists) { | |
try { | |
Timber.i("Creating file for today") | |
// Check if folder for logs exist | |
val root = File("${context.filesDir}/$logsDir") | |
if (!root.exists()) { | |
root.mkdirs() | |
} | |
File("${context.filesDir}/$logsDir/$stringDate$suffixName").createNewFile() | |
} catch (e: IOException) { | |
Timber.e(e) | |
} | |
} | |
// Finally write the log | |
try { | |
//BufferedWriter for performance, true to set append to file flag | |
val buf = BufferedWriter(FileWriter(File("${context.filesDir}/$logsDir/$stringDate$suffixName"), true)) | |
val time = SimpleDateFormat("HH.mm.ss", Locale.US).format(Date()) | |
buf.append(time) | |
buf.append("\t") | |
buf.append(targetText) | |
buf.newLine() | |
buf.close() | |
} catch (e: IOException) { | |
Timber.e(e, "Error appending log") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment