Skip to content

Instantly share code, notes, and snippets.

@cohenItay
Last active June 27, 2022 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cohenItay/f0c6c1024e4e633b4497e40fff27d6c8 to your computer and use it in GitHub Desktop.
Save cohenItay/f0c6c1024e4e633b4497e40fff27d6c8 to your computer and use it in GitHub Desktop.
class LogsFileProviderDaily @Inject constructor() : LogsFileProvider {
private val TAG = LogsFileProvider::class.simpleName!!
private val fileNameFormat = SimpleDateFormat("dd_MM_yyyy", Locale.getDefault())
override fun provideLogsDirectory(appContext: Context) =
File(("${appContext.filesDir}/${appContext.getString(R.string.logsDirectoryName)}"))
override suspend fun provideFile(appContext: Context): File? {
val fileName = fileNameFormat.format(Calendar.getInstance().time)
return getFileForToday(appContext, fileName)
}
private suspend fun getFileForToday(appContext: Context, fileName: String): File? = coroutineScope {
val folder = provideLogsDirectory(appContext)
if (!folder.exists() && !folder.mkdir())
return@coroutineScope null
val file = File(folder, "$fileName.log")
return@coroutineScope if (!file.exists()) {
withContext(Dispatchers.IO) {
try {
@Suppress("BlockingMethodInNonBlockingContext") // Inside Dispatchers.IO .. This context can be blocked. lint bug
if (file.createNewFile()) file else null
} catch (e: IOException) {
Log.e(TAG, "Problem creating the App log file", e)
null
}
}
} else {
file
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment