Skip to content

File Store

Tony Shen edited this page Mar 20, 2020 · 10 revisions

有些 App 对产生的日志有存储到文件的需求,L 的 file 模块提供了文件存储到 sdcard 的功能。

使用

通过 FileBuilder 可以构造一个 FilePrinter

        FileBuilder().folderPath(sdcardPath).fileNameGenerator(NetdiagnoseFileNameGenerator(
            PREFIX_APP
        )).cleanStrategy(cleanStrategy).build()

FileBuilder 构造的 FilePrinter 包含了文件名的生成策略、文件清理的策略。

一个完整的 LogManager ,

object LogManager {

    const val PREFIX_APP = "netdiagnose-app-"

    const val SEVEN_DAYS:Long = 24*3600*1000*7

    private val cleanStrategy = FileLastModifiedCleanStrategy(SEVEN_DAYS)

    val filePrinter: FilePrinter by lazy {

        var sdcardPath = "/sdcard/netdiagnose"
        val f = Environment.getExternalStorageDirectory()
        if (f != null) {
            sdcardPath = f.absolutePath + "/netdiagnose/app"
        }

        FileBuilder().folderPath(sdcardPath).fileNameGenerator(NetdiagnoseFileNameGenerator(
            PREFIX_APP
        )).cleanStrategy(cleanStrategy).build()
    }

    @JvmStatic
    fun initLog() {

        configL {

            header = "App Version ${App.CONTEXT.getAppVersion()}"

            converter = GsonConverter()
        }.apply {
            addPrinter(filePrinter)
        }
    }
}

适配 Android 10

targetSdkVersion 29

AndroidManifest.xml 中 application 添加如下的属性: android:requestLegacyExternalStorage="true"

Clone this wiki locally