Skip to content

Instantly share code, notes, and snippets.

@nikartx
Last active November 3, 2021 11:34
Show Gist options
  • Save nikartx/f0f4f02ebce11dc9c1179f410be6000f to your computer and use it in GitHub Desktop.
Save nikartx/f0f4f02ebce11dc9c1179f410be6000f to your computer and use it in GitHub Desktop.
Timber log to file txt
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="29"
tools:ignore="ScopedStorage" />
Use version 29 to work on Android 10. Need enable storage permission in app settings.
import android.os.Environment
import android.text.format.DateFormat
import android.util.Log
import ru.tander.magnit.BuildConfig
import timber.log.Timber
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.*
/**
* @author Ivan V on 20.10.2021
*
* To work correctly add to AndroidManifest:
* android:requestLegacyExternalStorage="true"
* For release builds:
* android:debuggable="true"
* tools:ignore="HardcodedDebugMode"
*
* See log in the dir: Documents/logs
*/
class FileLogTree : Timber.Tree() {
companion object {
private const val DEV_FILE_NAME = "Log.txt"
private const val PRD_FILE_NAME = "ReleaseLog.txt"
private const val LOG_DIR = "logs"
private const val DATE_FORMAT = "dd-MM-yyyy hh:mm:ss"
}
private val logFile: File by lazy {
val fileName = if (BuildConfig.DEBUG) DEV_FILE_NAME else PRD_FILE_NAME
val directory = Environment.getExternalStoragePublicDirectory(
"${Environment.DIRECTORY_DOCUMENTS}${File.separator}$LOG_DIR"
) ?: throw IOException("Incorrect logging file directory")
if (!directory.exists()) directory.mkdirs()
val file = File("${directory.absolutePath}${File.separator}$fileName")
if (!file.exists()) file.createNewFile()
file
}
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
// Ignore verbose logs
if (priority != Log.VERBOSE) {
val dateTime = Calendar.getInstance().time
val formatDateTime = DateFormat.format(DATE_FORMAT, dateTime)
try {
FileOutputStream(logFile, true).use {
it.write("$formatDateTime -> $message\n".toByteArray(Charsets.UTF_8))
}
} catch (e: IOException) {
Log.println(Log.ERROR,
this::class.java.simpleName,
"Error while logging into file: $e"
)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment