Last active
June 27, 2022 17:48
-
-
Save cohenItay/f0c6c1024e4e633b4497e40fff27d6c8 to your computer and use it in GitHub Desktop.
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
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