Skip to content

Commit 7a6faf6

Browse files
committed
增加日志存储到硬盘功能
1 parent 7e4bd7b commit 7a6faf6

File tree

8 files changed

+119
-168
lines changed

8 files changed

+119
-168
lines changed

app/src/main/java/com/catchpig/kmvvm/app/KotlinMvpApp.kt

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import com.catchpig.download.manager.DownloadManager
55
import com.catchpig.kmvvm.BuildConfig
66
import com.catchpig.kmvvm.R
77
import com.catchpig.mvvm.network.manager.NetManager
8-
import com.catchpig.utils.LogUtils
8+
import com.catchpig.utils.ext.initLogger
99
import com.scwang.smart.refresh.footer.ClassicsFooter
1010
import com.scwang.smart.refresh.header.MaterialHeader
1111
import com.scwang.smart.refresh.layout.SmartRefreshLayout
@@ -15,6 +15,9 @@ import com.scwang.smart.refresh.layout.SmartRefreshLayout
1515
* @date 2019/8/18 00:18
1616
*/
1717
class KotlinMvpApp : Application() {
18+
companion object {
19+
private const val TAG = "KotlinMvpApp"
20+
}
1821

1922
init {
2023
//设置全局的Header构建器
@@ -31,12 +34,16 @@ class KotlinMvpApp : Application() {
3134
override fun onCreate() {
3235
super.onCreate()
3336
val debug = BuildConfig.DEBUG
34-
// 框架内部已经初始化了,如果不需要打印日志的代码行数,就不需要再次初始化
35-
LogUtils.getInstance().showLineNumber(debug)
37+
initLogger()
3638
NetManager.getInstance().setDebug(debug)
3739
initDownload()
3840
}
3941

42+
private fun initLogger() {
43+
val path = "${externalCacheDir?.absolutePath}/logs"
44+
initLogger(path, "kmvvm")
45+
}
46+
4047
/**
4148
* 不是必须要设置下载路径,内部有默认的下载路径,如果需要变下载路径,请重新设置
4249
*/

mvvm/build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ android {
3636
viewBinding = true
3737
}
3838
}
39-
39+
Properties
4040
def dependenciesVersion = rootProject.dependenciesVersion
4141
dependencies {
4242
implementation fileTree(dir: 'libs', include: ['*.jar'])

mvvm/src/main/java/com/catchpig/mvvm/initializer/KotlinMvvmInitializer.kt

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,19 @@ import android.app.Application
44
import android.content.Context
55
import androidx.startup.Initializer
66
import com.catchpig.mvvm.lifecycle.ActivityLifeCycleCallbacksImpl
7-
import com.catchpig.utils.LogUtils
87
import com.catchpig.utils.ext.logd
98
import com.catchpig.utils.manager.ContextManager
9+
import com.orhanobut.logger.AndroidLogAdapter
10+
import com.orhanobut.logger.Logger
1011

1112
class KotlinMvvmInitializer : Initializer<Boolean> {
1213
companion object {
1314
private const val TAG = "KotlinMvvmInitializer"
1415
}
1516

1617
override fun create(context: Context): Boolean {
17-
val applicationContext = context!!.applicationContext
18-
initLog(applicationContext)
18+
val applicationContext = context.applicationContext
19+
initLog()
1920
initContext(applicationContext)
2021
"create".logd(TAG)
2122
return true
@@ -27,8 +28,8 @@ class KotlinMvvmInitializer : Initializer<Boolean> {
2728
application.registerActivityLifecycleCallbacks(ActivityLifeCycleCallbacksImpl())
2829
}
2930

30-
private fun initLog(context: Context) {
31-
LogUtils.getInstance().init(context)
31+
private fun initLog() {
32+
Logger.addLogAdapter(AndroidLogAdapter())
3233
}
3334

3435
override fun dependencies(): MutableList<Class<out Initializer<*>>> {

utils/build.gradle

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ dependencies {
4040
implementation "androidx.appcompat:appcompat:${dependenciesVersion["appcompat"]}"
4141
implementation "androidx.core:core-ktx:${dependenciesVersion["core_ktx"]}"
4242
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${dependenciesVersion["kotlin"]}"
43+
api "com.orhanobut:logger:${dependenciesVersion["logger"]}"
4344
api("com.google.android.material:material:${dependenciesVersion["material"]}")
4445

4546
api project(':annotation')

utils/src/main/java/com/catchpig/utils/LogUtils.kt

Lines changed: 0 additions & 152 deletions
This file was deleted.
Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,27 @@
11
package com.catchpig.utils.ext
22

3-
import com.catchpig.utils.LogUtils
3+
import android.os.HandlerThread
4+
import com.catchpig.utils.logger.MvvmDishLogStrategy
5+
import com.orhanobut.logger.CsvFormatStrategy
6+
import com.orhanobut.logger.DiskLogAdapter
7+
import com.orhanobut.logger.Logger
8+
9+
fun initLogger(path: String, tag: String) {
10+
val handlerThread = HandlerThread("mvvm-log")
11+
handlerThread.start()
12+
val handler = MvvmDishLogStrategy.WriteHandler(handlerThread.looper, path)
13+
val csvFormatStrategy =
14+
CsvFormatStrategy.newBuilder().logStrategy(MvvmDishLogStrategy(handler)).tag(tag).build()
15+
Logger.addLogAdapter(DiskLogAdapter(csvFormatStrategy))
16+
}
417

518
/**
619
*
720
* @author TLi2
821
**/
9-
fun String.logv(tag: String) = LogUtils.getInstance().vExt(tag, this)
10-
fun String.logd(tag: String) = LogUtils.getInstance().dExt(tag, this)
11-
fun String.logi(tag: String) = LogUtils.getInstance().iExt(tag, this)
12-
fun String.logw(tag: String) = LogUtils.getInstance().wExt(tag, this)
13-
fun String.loge(tag: String) = LogUtils.getInstance().eExt(tag, this)
22+
fun String.logv(tag: String) = Logger.v(tag, this)
23+
fun String.logd(tag: String) = Logger.d(tag, this)
24+
fun String.logi(tag: String) = Logger.i(tag, this)
25+
fun String.logw(tag: String) = Logger.w(tag, this)
26+
fun String.loge(tag: String) = Logger.e(tag, this)
1427

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package com.catchpig.utils.logger
2+
3+
import android.os.Handler
4+
import android.os.Looper
5+
import android.os.Message
6+
import com.orhanobut.logger.LogStrategy
7+
import java.io.File
8+
import java.io.FileWriter
9+
import java.io.IOException
10+
11+
class MvvmDishLogStrategy(private val handler: WriteHandler) : LogStrategy {
12+
companion object {
13+
private const val TAG = "MvvmDishLogStrategy"
14+
}
15+
16+
override fun log(level: Int, tag: String?, message: String) {
17+
handler.sendMessage(handler.obtainMessage(level, message))
18+
}
19+
20+
class WriteHandler(
21+
private val looper: Looper,
22+
private val folder: String,
23+
private val maxFileSize: Int = 10 * 1024 * 1024
24+
) : Handler(looper) {
25+
26+
override fun handleMessage(msg: Message) {
27+
val content = msg.obj as String
28+
29+
var fileWriter: FileWriter? = null
30+
val logFile = getLogFile(folder, "logs")
31+
32+
try {
33+
fileWriter = FileWriter(logFile, true)
34+
35+
writeLog(fileWriter, content)
36+
37+
fileWriter.flush()
38+
fileWriter.close()
39+
} catch (e: IOException) {
40+
if (fileWriter != null) {
41+
try {
42+
fileWriter.flush()
43+
fileWriter.close()
44+
} catch (e1: IOException) { /* fail silently */
45+
}
46+
}
47+
}
48+
}
49+
50+
private fun writeLog(fileWriter: FileWriter, content: String) {
51+
fileWriter.append(content)
52+
}
53+
54+
private fun getLogFile(folderName: String, fileName: String): File {
55+
val folder = File(folderName)
56+
if (!folder.exists()) {
57+
folder.mkdirs()
58+
}
59+
60+
var newFileCount = 0
61+
var newFile: File
62+
var existingFile: File? = null
63+
newFile = File(folder, String.format("%s_%s.log", fileName, newFileCount))
64+
while (newFile.exists()) {
65+
existingFile = newFile
66+
newFileCount++
67+
newFile = File(folder, String.format("%s_%s.log", fileName, newFileCount))
68+
}
69+
70+
if (existingFile != null) {
71+
if (existingFile.length() >= maxFileSize) {
72+
return newFile
73+
}
74+
return existingFile
75+
}
76+
77+
return newFile
78+
}
79+
}
80+
}

version.gradle

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ ext {
4545
'coroutines' : '1.6.4',
4646
'serialization' : '1.4.1',
4747
'lifecycle' : '2.6.1',
48-
"ksp" : '2.0.21-1.0.26'
48+
"ksp" : '2.0.21-1.0.26',
49+
"logger" : "2.2.0"
4950
]
5051
}
5152

0 commit comments

Comments
 (0)