Skip to content

Instantly share code, notes, and snippets.

@DevPicon
Created February 12, 2019 18:59
Show Gist options
  • Save DevPicon/176a5a367c7369e44875edb52a671459 to your computer and use it in GitHub Desktop.
Save DevPicon/176a5a367c7369e44875edb52a671459 to your computer and use it in GitHub Desktop.
import android.os.Environment
import android.util.Log
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.IOException
object LocalLogger {
// USAGE: LocalLogger.INSTANCE.log(TAG, "------ updateProduct() -----");
lateinit var logFile: File
fun getFile() {
val directory = File(Environment.getExternalStorageDirectory(), "shoppers/logs")
val directoriesCreated = directory.exists() || directory.mkdirs()
if (directoriesCreated) {
logFile = File(directory, "local-logger.txt")
if (!logFile.exists()) {
val fileCreated = logFile.createNewFile()
if (!fileCreated) {
throw NoFileException()
}
}
} else {
throw NoFileException()
}
}
fun log(className: String, text: String) {
getFile()
writeToFile("$className : $text")
}
private fun writeToFile(data: String) {
try {
val fileWriter = BufferedWriter(FileWriter(logFile, true))
fileWriter.write(data + "\n")
fileWriter.close()
} catch (e: IOException) {
Log.e("Exception", "File write failed: $e")
}
}
}
class NoFileException : Exception()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment