Browse Source

提交1.1.2版本,优化写入文件方法,优化初始化配置,kotlin单独提交ktx包

kth_win_android 3 years ago
parent
commit
5cdb5cff85
31 changed files with 1220 additions and 113 deletions
  1. 28 9
      README.md
  2. 3 2
      app/build.gradle
  3. 2 0
      app/src/main/AndroidManifest.xml
  4. 4 1
      app/src/main/java/com/mylove/logger/AppContext.kt
  5. 15 3
      app/src/main/java/com/mylove/logger/MainActivity.kt
  6. 1 0
      loglib-kt/.gitignore
  7. 28 0
      loglib-kt/bintrayUpload.gradle
  8. 42 0
      loglib-kt/build.gradle
  9. 0 0
      loglib-kt/consumer-rules.pro
  10. 21 0
      loglib-kt/proguard-rules.pro
  11. 24 0
      loglib-kt/src/androidTest/java/com/kth/loglib_kt/ExampleInstrumentedTest.kt
  12. 5 0
      loglib-kt/src/main/AndroidManifest.xml
  13. 181 0
      loglib-kt/src/main/java/com/benyanyi/loglib/BaseLog.kt
  14. 68 0
      loglib-kt/src/main/java/com/benyanyi/loglib/FileLog.kt
  15. 347 0
      loglib-kt/src/main/java/com/benyanyi/loglib/Jlog.kt
  16. 47 0
      loglib-kt/src/main/java/com/benyanyi/loglib/JsonLog.kt
  17. 4 0
      loglib-kt/src/main/java/com/benyanyi/loglib/KtUtils.kt
  18. 62 0
      loglib-kt/src/main/java/com/benyanyi/loglib/LogConfig.kt
  19. 11 0
      loglib-kt/src/main/java/com/benyanyi/loglib/LogType.kt
  20. 51 0
      loglib-kt/src/main/java/com/benyanyi/loglib/LogUtil.kt
  21. 62 0
      loglib-kt/src/main/java/com/benyanyi/loglib/XmlLog.kt
  22. 17 0
      loglib-kt/src/test/java/com/kth/loglib_kt/ExampleUnitTest.kt
  23. 0 5
      loglib/build.gradle
  24. 34 29
      loglib/src/main/java/com/benyanyi/loglib/BaseLog.java
  25. 1 1
      loglib/src/main/java/com/benyanyi/loglib/FileLog.java
  26. 45 57
      loglib/src/main/java/com/benyanyi/loglib/Jlog.java
  27. 8 2
      loglib/src/main/java/com/benyanyi/loglib/JsonLog.java
  28. 84 0
      loglib/src/main/java/com/benyanyi/loglib/LogConfig.java
  29. 15 1
      loglib/src/main/java/com/benyanyi/loglib/LogUtil.java
  30. 9 3
      loglib/src/main/java/com/benyanyi/loglib/XmlLog.java
  31. 1 0
      settings.gradle

+ 28 - 9
README.md

@@ -4,7 +4,7 @@
 
 ## 使用方法
 
-### 根目录下build.gradle添加Maven地址
+### 如果你的项目 Gradle 配置是在 7.0 以下,需要在 build.gradle 文件中加入
 
 ~~~
 repositories {
@@ -14,25 +14,33 @@ repositories {
     }
 ~~~
 
+### 如果你的 Gradle 配置是 7.0 及以上,则需要在 settings.gradle 文件中加入
+~~~
+dependencyResolutionManagement {
+    repositories {
+        maven {
+            allowInsecureProtocol = true
+            url "http://www.benyanyi.com/repository/benyanyi/"
+        }
+    }
+}
+~~~
+
 ### module 下添加
 
 ~~~
-implementation 'com.yanyi.benyanyi:Logger:1.1.1'
+implementation 'com.yanyi.benyanyi:Logger:1.1.2'
 ~~~
 
-或者
+kotlin版本
 
 ~~~
-<dependency>
-  <groupId>com.yanyi.benyanyi</groupId>
-  <artifactId>Logger</artifactId>
-  <version>1.1.1</version>
-  <type>aar</type>
-</dependency>
+implementation 'com.yanyi.benyanyi:Logger-kt:1.1.2'
 ~~~
 
 ### 参数介绍
 
+* 初始化配置成LogConfig,<font color="#ff0000">住:写入文件需要先获取文件读写权限</font>
 * JLog.init {isShowLog}设置是否打印,默认debug版本apk打印,release版本apk不打印;{tag}设置打印标签,默认为Jlog;{isWrite(1.0.6版本添加)
   }设置是否每条日志都输出到设备文件夹中,默认不输入
 * JLog.fileType(FileType) 设置打印方式,默认FileType为FileType.JAVA,说明为java类打印
@@ -43,6 +51,16 @@ implementation 'com.yanyi.benyanyi:Logger:1.1.1'
 * JLog.debug 打印debug日志
 * JLog.errorWriteFile 异常写入文件
 
+#### 1.1.2版本添加
+
+* setNullTip 为空时提示信息
+* setTagDefault 默认标签
+* setTag 标签
+* setShowLog 是否显示log
+* setWrite 是否写入文件夹
+* setWriteRootPath 写入文件夹根目录
+* setShowWrite 是否显示log的时候也写入文件夹
+
 #### 1.0.6版本添加
 
 * JLog.writeFile 日志输出到设备文件夹
@@ -50,6 +68,7 @@ implementation 'com.yanyi.benyanyi:Logger:1.1.1'
 
 ## 更新
 
+* 2022-11-30 更新1.1.2,将kotlin版本单独出来,并将初始化配置成LogConfig
 * 2022-11-22 更新1.1.1,优化日志写入文件方法,优化文件名显示,添加kotlin打印调用
 * 2022-07-26 更新1.0.8,完善打印文件夹参数配置
 * 2022-05-01 更新1.0.7,自动识别打印文件类型

+ 3 - 2
app/build.gradle

@@ -44,8 +44,9 @@ dependencies {
     testImplementation 'junit:junit:4.13'
     androidTestImplementation 'androidx.test.ext:junit:1.1.2'
     androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
-    implementation project(':loglib')
-    implementation 'com.yanyi.benyanyi:PermissionHelper:1.1.4'
+    implementation project(':loglib-kt')
+    implementation 'com.yanyi.benyanyi:PermissionHelper:1.1.8'
+//    implementation 'com.yanyi.benyanyi:Logger-ktx:1.1.1-base2'
     implementation "androidx.core:core-ktx:1.3.2"
     implementation "org.jetbrains.kotlin:kotlin-stdlib:1.5.30"
 }

+ 2 - 0
app/src/main/AndroidManifest.xml

@@ -2,12 +2,14 @@
     package="com.mylove.logger">
 
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 
     <application
         android:name=".AppContext"
         android:allowBackup="true"
         android:icon="@mipmap/ic_launcher"
         android:label="@string/app_name"
+        android:requestLegacyExternalStorage="true"
         android:roundIcon="@mipmap/ic_launcher_round"
         android:supportsRtl="true"
         android:theme="@style/AppTheme">

+ 4 - 1
app/src/main/java/com/mylove/logger/AppContext.kt

@@ -13,7 +13,10 @@ class AppContext : Application() {
     override fun onCreate() {
         super.onCreate()
         //        Jlog.init(BuildConfig.LOG_DEBUG);
-        Jlog.init(true, true)
+        Jlog.init()
+            .setShowLog(true)
+            .setWrite(true)
+            .setShowWrite(true)
     }
 
 }

+ 15 - 3
app/src/main/java/com/mylove/logger/MainActivity.kt

@@ -1,5 +1,6 @@
 package com.mylove.logger
 
+import android.Manifest
 import android.annotation.SuppressLint
 import android.app.Application
 import android.content.pm.ApplicationInfo
@@ -7,7 +8,9 @@ import android.os.Bundle
 import android.widget.TextView
 import androidx.appcompat.app.AppCompatActivity
 import com.benyanyi.loglib.Jlog
-import com.benyanyi.loglib.v
+import com.benyanyi.loglib.LogConfig
+import com.benyanyi.permissionlib.PermissionHelper
+import com.benyanyi.permissionlib.callback.PermissionCallBack
 
 /**
  * @author myLove
@@ -24,8 +27,17 @@ class MainActivity : AppCompatActivity() {
         //        tv.setText(isApkInDebug() + "");
 //        Jlog.v("测试" + isApkInDebug());
 //        Jlog.d("测试")
-        "测试".v()
-        Jlog.json("{\"name\":\"BeJson\",\"url\":\"http://www.bejson.com\",\"page\":88,\"isNonProfit\":true,\"address\":{\"street\":\"科技园路.\",\"city\":\"江苏苏州\",\"country\":\"中国\"},\"links\":[{\"name\":\"Google\",\"url\":\"http://www.google.com\"},{\"name\":\"Baidu\",\"url\":\"http://www.baidu.com\"},{\"name\":\"SoSo\",\"url\":\"http://www.SoSo.com\"}]}")
+        PermissionHelper.with(this)
+            .setPermissions(
+                Manifest.permission.WRITE_EXTERNAL_STORAGE,
+                Manifest.permission.READ_EXTERNAL_STORAGE
+            ).request(object : PermissionCallBack() {
+                override fun onSuccess() {
+//                    Jlog.d()
+                    Jlog.json("{\"name\":\"BeJson\",\"url\":\"http://www.bejson.com\",\"page\":88,\"isNonProfit\":true,\"address\":{\"street\":\"科技园路.\",\"city\":\"江苏苏州\",\"country\":\"中国\"},\"links\":[{\"name\":\"Google\",\"url\":\"http://www.google.com\"},{\"name\":\"Baidu\",\"url\":\"http://www.baidu.com\"},{\"name\":\"SoSo\",\"url\":\"http://www.SoSo.com\"}]}")
+//                    Jlog.v("啊哈111")
+                }
+            })
 //        PermissionHelper.getInstance(this).hasPermission(0x10, object : PermissionCallBack {
 //            override fun onPermissionSuccess(i: Int) {
 //                Jlog.writeFile("啊哈")

+ 1 - 0
loglib-kt/.gitignore

@@ -0,0 +1 @@
+/build

+ 28 - 0
loglib-kt/bintrayUpload.gradle

@@ -0,0 +1,28 @@
+apply plugin: 'maven-publish'
+apply plugin: 'maven'
+
+Properties properties = new Properties()
+properties.load(project.rootProject.file('local.properties').newDataInputStream())
+uploadArchives {
+    repositories {
+        mavenDeployer {
+            repository(url: properties.getProperty("POM_URL")) {
+                authentication(userName: properties.getProperty("nexus.user"), password: properties.getProperty("nexus.password"))
+            }
+
+            pom.groupId = properties.getProperty("POM_GROUP_ID")
+            pom.artifactId = properties.getProperty("POM_ATRIFACT_KT_ID")
+            pom.version = properties.getProperty("POM_VERSION")
+
+            pom.project {
+                licenses {
+                    license {
+                        name 'The Apache Software License, Version 2.0'
+                        url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
+                    }
+                }
+            }
+        }
+    }
+}
+//gradlew uploadArchives    terminal中输入

+ 42 - 0
loglib-kt/build.gradle

@@ -0,0 +1,42 @@
+apply plugin: 'com.android.library'
+apply plugin: 'kotlin-android'
+//apply plugin: 'com.github.dcendents.android-maven'
+
+android {
+    compileSdkVersion 29
+
+
+
+    defaultConfig {
+        minSdkVersion 14
+        targetSdkVersion 29
+        versionCode 1
+        versionName "1.0"
+
+        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+
+    }
+
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+
+}
+
+dependencies {
+    implementation fileTree(dir: 'libs', include: ['*.jar'])
+
+    implementation 'androidx.appcompat:appcompat:1.2.0'
+    testImplementation 'junit:junit:4.13'
+    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
+    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
+    implementation "androidx.core:core-ktx:1.3.2"
+    implementation "org.jetbrains.kotlin:kotlin-stdlib:1.5.30"
+}
+apply from: 'bintrayUpload.gradle'
+repositories {
+    mavenCentral()
+}

+ 0 - 0
loglib-kt/consumer-rules.pro


+ 21 - 0
loglib-kt/proguard-rules.pro

@@ -0,0 +1,21 @@
+# Add project specific ProGuard rules here.
+# You can control the set of applied configuration files using the
+# proguardFiles setting in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
+
+# Uncomment this to preserve the line number information for
+# debugging stack traces.
+#-keepattributes SourceFile,LineNumberTable
+
+# If you keep the line number information, uncomment this to
+# hide the original source file name.
+#-renamesourcefileattribute SourceFile

+ 24 - 0
loglib-kt/src/androidTest/java/com/kth/loglib_kt/ExampleInstrumentedTest.kt

@@ -0,0 +1,24 @@
+package com.kth.loglib_kt
+
+import androidx.test.platform.app.InstrumentationRegistry
+import androidx.test.ext.junit.runners.AndroidJUnit4
+
+import org.junit.Test
+import org.junit.runner.RunWith
+
+import org.junit.Assert.*
+
+/**
+ * Instrumented test, which will execute on an Android device.
+ *
+ * See [testing documentation](http://d.android.com/tools/testing).
+ */
+@RunWith(AndroidJUnit4::class)
+class ExampleInstrumentedTest {
+    @Test
+    fun useAppContext() {
+        // Context of the app under test.
+        val appContext = InstrumentationRegistry.getInstrumentation().targetContext
+        assertEquals("com.kth.loglib_kt.test", appContext.packageName)
+    }
+}

+ 5 - 0
loglib-kt/src/main/AndroidManifest.xml

@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.benyanyi.loglib">
+
+</manifest>

+ 181 - 0
loglib-kt/src/main/java/com/benyanyi/loglib/BaseLog.kt

@@ -0,0 +1,181 @@
+package com.benyanyi.loglib
+
+import android.app.Application
+import android.os.Environment
+import android.text.TextUtils
+import android.util.Log
+import java.io.*
+import java.text.SimpleDateFormat
+import java.util.*
+
+/**
+ * @author myLove
+ * @time 2017/10/31 10:41
+ * @e-mail ben@yanyi.red
+ * @overview
+ */
+internal object BaseLog {
+    private const val MAX_LENGTH = 4000
+    fun printDefault(type: LogType, tag: String, msg: String) {
+        var index = 0
+        val length = msg.length
+        val countOfSub = length / MAX_LENGTH
+        if (countOfSub > 0) {
+            for (i in 0 until countOfSub) {
+                val sub = msg.substring(index, index + MAX_LENGTH)
+                printSub(type, tag, sub)
+                index += MAX_LENGTH
+            }
+            printSub(type, tag, msg.substring(index, length))
+        } else {
+            printSub(type, tag, msg)
+        }
+    }
+
+    private fun printSub(type: LogType, tag: String, sub: String) {
+        if (Jlog.mConfig.isShowLog || Jlog.IS_INIT) {
+            when (type) {
+                LogType.V -> Log.v(tag, sub)
+                LogType.D -> Log.d(tag, sub)
+                LogType.I -> Log.i(tag, sub)
+                LogType.W -> Log.w(tag, sub)
+                LogType.E -> Log.e(tag, sub)
+                LogType.A -> Log.wtf(tag, sub)
+            }
+        }
+        if (!Jlog.mConfig.isWrite) {
+            return
+        }
+        if (!Jlog.mConfig.isShowWrite && Jlog.mConfig.isShowLog) {
+            return
+        }
+        writeLog(tag, sub)
+    }
+
+    /**
+     * 记录报错日志
+     */
+    fun writeError(tag: String, throwable: Throwable) {
+        val writer = StringWriter()
+        val printWriter = PrintWriter(writer)
+        throwable.printStackTrace(printWriter)
+        var cause = throwable.cause
+        while (cause != null) {
+            cause.printStackTrace(printWriter)
+            cause = cause.cause
+        }
+        printWriter.close()
+        val s = writer.toString()
+        writeLog(tag, s)
+    }
+
+    /**
+     * 记录日志
+     */
+    @JvmStatic
+    fun writeLog(tag: String, exceptionDescription: String?) {
+        try {
+            val ROOT_PATH: String
+            if (TextUtils.isEmpty(Jlog.mConfig.writeRootPath) || Jlog.mConfig.writeRootPath.equals(
+                    "null",
+                    ignoreCase = true
+                )
+            ) {
+                val application =
+                    Class.forName("android.app.ActivityThread").getMethod("currentApplication")
+                        .invoke(null, *(null ?: arrayOfNulls<Any>(0))) as Application
+                val packageName = application.packageName
+                if (exceptionDescription == null || TextUtils.isEmpty(packageName)) {
+                    return
+                }
+                val fileName: String
+                val split = packageName.split("\\.".toRegex()).toTypedArray()
+                fileName = split[split.size - 1]
+                ROOT_PATH =
+                    Environment.getExternalStorageDirectory().toString() + "/" + fileName + "/"
+            } else {
+                ROOT_PATH = Jlog.mConfig.writeRootPath
+            }
+            val rootFile = File(ROOT_PATH)
+            try {
+                if (!rootFile.exists()) {
+                    rootFile.mkdir()
+                }
+            } catch (e: Exception) {
+                e.printStackTrace()
+            }
+            val logPath = File("$ROOT_PATH/log/")
+            try {
+                if (!logPath.exists()) {
+                    logPath.mkdir()
+                }
+            } catch (e: Exception) {
+                e.printStackTrace()
+            }
+            val simpleDateFormat = SimpleDateFormat("yyyyMMdd", Locale.CHINA) // HH:mm:ss
+            //获取当前时间
+            val date = Date(System.currentTimeMillis())
+            val logFile = File(logPath.toString() + "/" + simpleDateFormat.format(date) + ".txt")
+            try {
+                if (logPath.exists() && !logFile.exists()) {
+                    logFile.createNewFile()
+                }
+            } catch (e: Exception) {
+            }
+            var fw: FileWriter? = null
+            if (logFile.exists()) {
+                try {
+                    fw = FileWriter(logFile, true)
+                    if (TextUtils.isEmpty(tag)) {
+                        fw.write(timeString + "\t\t" + exceptionDescription + "\r\n")
+                    } else {
+                        fw.write(timeString + "\t\t" + tag + "\t\t" + exceptionDescription + "\r\n")
+                    }
+                } catch (e: Exception) {
+                    e.printStackTrace()
+                } finally {
+                    fw?.close()
+                }
+            }
+        } catch (e: Exception) {
+            e.printStackTrace()
+        }
+    }
+
+    private fun getFileSizes(f: File): Long {
+        var s: Long = 0
+        if (f.exists()) {
+            var fis: FileInputStream? = null
+            try {
+                fis = FileInputStream(f)
+            } catch (e: FileNotFoundException) {
+                e.printStackTrace()
+            }
+            try {
+                assert(fis != null)
+                s = fis!!.available().toLong()
+            } catch (e: Exception) {
+                e.printStackTrace()
+            }
+        } else {
+            try {
+                f.createNewFile()
+            } catch (e: IOException) {
+                e.printStackTrace()
+            }
+            println("文件不存在")
+        }
+        return s
+    }
+
+    /**
+     * 获取时间
+     *
+     * @return str
+     */
+    val timeString: String
+        get() {
+            val dateStr = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)
+            return dateStr.format(Date())
+        }
+}

+ 68 - 0
loglib-kt/src/main/java/com/benyanyi/loglib/FileLog.kt

@@ -0,0 +1,68 @@
+package com.benyanyi.loglib
+
+import android.util.Log
+import java.io.*
+import java.lang.Exception
+import java.util.*
+
+/**
+ * @author myLove
+ * @time 2017/10/31 10:40
+ * @e-mail ben@yanyi.red
+ * @overview
+ */
+internal object FileLog {
+    private const val FILE_PREFIX = "JLog_"
+    private const val FILE_FORMAT = ".log"
+    fun printFile(
+        tag: String?,
+        targetDirectory: File,
+        fileName: String?,
+        headString: String,
+        msg: String
+    ) {
+        val fileNames = fileName ?: FileLog.fileName
+        if (save(targetDirectory, fileNames, msg)) {
+            Log.d(
+                tag,
+                headString + " save log success ! location is >>>" + targetDirectory.absolutePath + "/" + fileNames
+            )
+        } else {
+            Log.e(tag, headString + "save log fails !")
+        }
+    }
+
+    private fun save(dic: File, fileName: String, msg: String): Boolean {
+        val file = File(dic, fileName)
+        return try {
+            val outputStream: OutputStream = FileOutputStream(file)
+            val outputStreamWriter = OutputStreamWriter(outputStream, "UTF-8")
+            outputStreamWriter.write(msg)
+            outputStreamWriter.flush()
+            outputStream.close()
+            true
+        } catch (e: FileNotFoundException) {
+            e.printStackTrace()
+            false
+        } catch (e: UnsupportedEncodingException) {
+            e.printStackTrace()
+            false
+        } catch (e: IOException) {
+            e.printStackTrace()
+            false
+        } catch (e: Exception) {
+            e.printStackTrace()
+            false
+        }
+    }
+
+    private val fileName: String
+        get() {
+            val random = Random()
+            return FILE_PREFIX + java.lang.Long.toString(
+                System.currentTimeMillis() + random.nextInt(
+                    10000
+                )
+            ).substring(4) + FILE_FORMAT
+        }
+}

+ 347 - 0
loglib-kt/src/main/java/com/benyanyi/loglib/Jlog.kt

@@ -0,0 +1,347 @@
+package com.benyanyi.loglib
+
+import android.text.TextUtils
+import java.io.File
+import java.io.PrintWriter
+import java.io.StringWriter
+import java.lang.StringBuilder
+
+/**
+ * @author myLove
+ * @time 2017/10/31 10:39
+ * @e-mail ben@yanyi.red
+ * @overview
+ */
+object Jlog {
+    @JvmField
+    internal val LINE_SEPARATOR = System.getProperty("line.separator")
+    private const val DEFAULT_MESSAGE = "********"
+    private const val PARAM = "Param"
+    private const val NULL = "null"
+    internal const val JSON_INDENT = 4
+
+    @JvmField
+    internal var mIsGlobalTagEmpty = true
+
+    @JvmField
+    internal var IS_INIT = true
+
+    @JvmField
+    internal var mConfig = LogConfig()
+
+    fun init(): LogConfig {
+        return mConfig
+    }
+
+    fun init(config: LogConfig) {
+        mConfig = config
+    }
+
+    fun v() {
+        printLog(LogType.V, null, DEFAULT_MESSAGE)
+    }
+
+    fun v(msg: Any?) {
+        printLog(LogType.V, null, msg!!)
+    }
+
+    fun v(length: Int, msg: Any?) {
+        printLog(LogType.V, null, msg!!)
+    }
+
+    fun v(tag: Any?, vararg objects: Any) {
+        printLog(LogType.V, tag, *objects)
+    }
+
+    fun d() {
+        printLog(LogType.D, null, DEFAULT_MESSAGE)
+    }
+
+    fun d(msg: Any?) {
+        printLog(LogType.D, null, msg!!)
+    }
+
+    fun d(tag: Any?, vararg objects: Any?) {
+        printLog(LogType.D, tag, *objects)
+    }
+
+    fun i() {
+        printLog(LogType.I, null, DEFAULT_MESSAGE)
+    }
+
+    fun i(msg: Any?) {
+        printLog(LogType.I, null, msg!!)
+    }
+
+    fun i(tag: Any?, vararg objects: Any?) {
+        printLog(LogType.I, tag, *objects)
+    }
+
+    fun w() {
+        printLog(LogType.W, null, DEFAULT_MESSAGE)
+    }
+
+    fun w(msg: Any?) {
+        printLog(LogType.W, null, msg!!)
+    }
+
+    fun w(tag: Any?, vararg objects: Any?) {
+        printLog(LogType.W, tag, *objects)
+    }
+
+    fun e() {
+        printLog(LogType.E, null, DEFAULT_MESSAGE)
+    }
+
+    fun e(msg: Any?) {
+        printLog(LogType.E, null, msg!!)
+    }
+
+    fun e(tag: Any?, vararg objects: Any?) {
+        printLog(LogType.E, tag, *objects)
+    }
+
+    fun a() {
+        printLog(LogType.A, null, DEFAULT_MESSAGE)
+    }
+
+    fun a(msg: Any?) {
+        printLog(LogType.A, null, msg!!)
+    }
+
+    fun a(tag: Any?, vararg objects: Any?) {
+        printLog(LogType.A, tag, *objects)
+    }
+
+    fun json(jsonFormat: Any?) {
+        printLog(LogType.JSON, null, jsonFormat!!)
+    }
+
+    fun json(tag: Any?, jsonFormat: String?) {
+        printLog(LogType.JSON, tag, jsonFormat!!)
+    }
+
+    fun xml(xml: Any?) {
+        printLog(LogType.XML, null, xml!!)
+    }
+
+    fun xml(tag: Any?, xml: String?) {
+        printLog(LogType.XML, tag, xml!!)
+    }
+
+    fun file(targetDirectory: File, msg: Any) {
+        printFile(null, targetDirectory, null, msg)
+    }
+
+    fun file(tag: Any?, targetDirectory: File, msg: Any) {
+        printFile(tag, targetDirectory, null, msg)
+    }
+
+    fun file(tag: Any?, targetDirectory: File, fileName: String?, msg: Any) {
+        printFile(tag, targetDirectory, fileName, msg)
+    }
+
+    fun debug() {
+        printDebug(null, DEFAULT_MESSAGE)
+    }
+
+    fun debug(msg: Any?) {
+        printDebug(null, msg!!)
+    }
+
+    fun debug(tag: Any?, vararg objects: Any?) {
+        printDebug(tag, *objects)
+    }
+
+    fun trace() {
+        printStackTrace()
+    }
+
+    fun errorWriteFile(throwable: Throwable) {
+        if (mConfig.isWrite) {
+            BaseLog.writeError(mConfig.tag ?: "", throwable)
+        }
+    }
+
+    fun errorWriteFile(tag: String, throwable: Throwable) {
+        if (mConfig.isWrite) {
+            BaseLog.writeError(tag, throwable)
+        }
+    }
+
+    private fun printStackTrace() {
+        if (!IS_INIT && !mConfig.isWrite) {
+            return
+        }
+        if (!mConfig.isShowLog && isApkInDebug && !mConfig.isWrite) {
+            return
+        }
+        val tr = Throwable()
+        val sw = StringWriter()
+        val pw = PrintWriter(sw)
+        tr.printStackTrace(pw)
+        pw.flush()
+        val message = sw.toString()
+        val traceString = message.split("\\n\\t".toRegex()).toTypedArray()
+        val sb = StringBuilder()
+        sb.append("\n")
+        for (trace in traceString) {
+            if (trace.contains("at Jlog")) {
+                continue
+            }
+            sb.append(trace).append("\n")
+        }
+        val contents = wrapperContent("null", sb.toString()) ?: return
+        val tag = contents[0]
+        val msg = contents[1]
+        val headString = contents[2]
+        BaseLog.printDefault(LogType.D, tag, headString + msg)
+    }
+
+    private fun printLog(type: LogType, tagStr: Any?, vararg objects: Any?) {
+        if (!IS_INIT && !mConfig.isWrite) {
+            return
+        }
+        if (!mConfig.isShowLog && isApkInDebug && !mConfig.isWrite) {
+            return
+        }
+        val contents = wrapperContent(tagStr, *objects) ?: return
+        val tag = contents[0]
+        val msg = contents[1]
+        val headString = contents[2]
+        when (type) {
+            LogType.V, LogType.D, LogType.I, LogType.W, LogType.E, LogType.A -> BaseLog.printDefault(
+                type,
+                tag,
+                headString + msg
+            )
+            LogType.JSON -> JsonLog.printJson(tag, msg, headString)
+            LogType.XML -> XmlLog.printXml(tag, msg, headString)
+        }
+    }
+
+    private fun printDebug(tagStr: Any?, vararg objects: Any?) {
+        if (!IS_INIT || !mConfig.isWrite) {
+            return
+        }
+        val contents = wrapperContent(tagStr, *objects) ?: return
+        val tag = contents[0]
+        val msg = contents[1]
+        val headString = contents[2]
+        BaseLog.printDefault(LogType.D, tag, headString + msg)
+    }
+
+    private fun printFile(tagStr: Any?, targetDirectory: File, fileName: String?, objectMsg: Any) {
+        if (!IS_INIT && !mConfig.isWrite) {
+            return
+        }
+        if (!mConfig.isShowLog && isApkInDebug && !mConfig.isWrite) {
+            return
+        }
+        val contents = wrapperContent(tagStr, objectMsg) ?: return
+        val tag = contents[0]
+        val msg = contents[1]
+        val headString = contents[2]
+        FileLog.printFile(tag, targetDirectory, fileName, headString, msg)
+    }
+
+    private fun wrapperContent(tagStr: Any?, vararg objects: Any?): Array<String>? {
+        val stackTrace = Thread.currentThread().stackTrace
+        var fileName = ""
+        var targetElement: StackTraceElement? = null
+        for (element in stackTrace) {
+            val name = element.fileName
+            val packageName = element.javaClass.getPackage()!!.name
+            if ("VMStack.java" != name && "Thread.java" != name && "Jlog.kt" != name
+                && "KtUtils.kt" != name
+            ) {
+                fileName = name
+                targetElement = element
+                break
+            }
+        }
+        if (targetElement == null) {
+            return null
+        }
+        val str = "$"
+        if (fileName.contains(str)) {
+            fileName = fileName.split("\\$".toRegex()).toTypedArray()[0]
+        }
+        val methodName = targetElement.methodName
+        var lineNumber = targetElement.lineNumber
+        if (lineNumber < 0) {
+            lineNumber = 0
+        }
+        var tag = (tagStr ?: fileName).toString()
+        if (mIsGlobalTagEmpty && TextUtils.isEmpty(tag)) {
+            tag = mConfig.tagDefault
+        } else if (!mIsGlobalTagEmpty) {
+            tag = mConfig.tagDefault
+        }
+        val msg = getObjectsString(*objects)
+        val headString = "[ ($fileName:$lineNumber)#$methodName ] "
+        return arrayOf(tag, msg, headString)
+    }
+
+    private fun getObjectsString(vararg objects: Any?): String {
+        return if (objects.size > 1) {
+            val stringBuilder = StringBuilder()
+            stringBuilder.append("\n")
+            for (i in objects.indices) {
+                val `object` = objects[i]
+                if (`object` == null) {
+                    stringBuilder.append(PARAM).append("[").append(i).append("]").append(" = ")
+                        .append(
+                            NULL
+                        ).append("\n")
+                } else {
+                    stringBuilder.append(PARAM).append("[").append(i).append("]").append(" = ")
+                        .append(`object`).append("\n")
+                }
+            }
+            stringBuilder.toString()
+        } else {
+            val `object` = objects[0]
+            `object`?.toString() ?: NULL
+        }
+    }
+
+    //        try {
+//            @SuppressLint("PrivateApi")
+//            Class<?> activityThread = Class.forName("android.app.ActivityThread");
+//            Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
+//            Object app = activityThread.getMethod("getApplication").invoke(thread);
+//            Application application;
+//            if (app == null) {
+//                application = null;
+//            } else {
+//                application = (Application) app;
+//            }
+//            ApplicationInfo info = application.getApplicationInfo();
+//            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0;
+//        } catch (Exception e) {
+//            return false;
+//        }
+    private val isApkInDebug: Boolean
+        get() = BuildConfig.DEBUG
+    //        try {
+//            @SuppressLint("PrivateApi")
+//            Class<?> activityThread = Class.forName("android.app.ActivityThread");
+//            Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
+//            Object app = activityThread.getMethod("getApplication").invoke(thread);
+//            Application application;
+//            if (app == null) {
+//                application = null;
+//            } else {
+//                application = (Application) app;
+//            }
+//            ApplicationInfo info = application.getApplicationInfo();
+//            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0;
+//        } catch (Exception e) {
+//            return false;
+//        }
+
+
+    fun aaa(vararg str: String) {}
+
+}

+ 47 - 0
loglib-kt/src/main/java/com/benyanyi/loglib/JsonLog.kt

@@ -0,0 +1,47 @@
+package com.benyanyi.loglib
+
+import android.util.Log
+import org.json.JSONObject
+import org.json.JSONArray
+import org.json.JSONException
+
+/**
+ * @author myLove
+ * @time 2017/10/31 10:42
+ * @e-mail ben@yanyi.red
+ * @overview
+ */
+internal object JsonLog {
+    fun printJson(tag: String, msg: String, headString: String) {
+        var message: String
+        val str1 = "{"
+        val str2 = "["
+        message = try {
+            if (msg.startsWith(str1)) {
+                val jsonObject = JSONObject(msg)
+                jsonObject.toString(Jlog.JSON_INDENT)
+            } else if (msg.startsWith(str2)) {
+                val jsonArray = JSONArray(msg)
+                jsonArray.toString(Jlog.JSON_INDENT)
+            } else {
+                msg
+            }
+        } catch (e: JSONException) {
+            msg
+        }
+        LogUtil.printLine(tag, true)
+        message = headString + Jlog.LINE_SEPARATOR + message
+        val lines = message.split(Jlog.LINE_SEPARATOR!!.toRegex()).toTypedArray()
+        for (line in lines) {
+            Log.d(tag, "║ $line")
+            if (!Jlog.mConfig.isWrite) {
+                return
+            }
+            if (!Jlog.mConfig.isShowWrite && Jlog.mConfig.isShowLog) {
+                return
+            }
+            BaseLog.writeLog(tag, "║ $line")
+        }
+        LogUtil.printLine(tag, false)
+    }
+}

+ 4 - 0
loglib/src/main/java/com/benyanyi/loglib/KtUtils.kt → loglib-kt/src/main/java/com/benyanyi/loglib/KtUtils.kt

@@ -8,6 +8,10 @@ import java.io.File
  * @user yanyi
  * @overview
  */
+fun LogConfig.init() {
+    Jlog.init(this)
+}
+
 fun Any?.v() {
     Jlog.v(this)
 }

+ 62 - 0
loglib-kt/src/main/java/com/benyanyi/loglib/LogConfig.kt

@@ -0,0 +1,62 @@
+package com.benyanyi.loglib
+
+import android.text.TextUtils
+
+/**
+ * @author myLove
+ * @date 2022/11/30 13:21
+ * @email ben@yanyi.red
+ * @overview
+ */
+class LogConfig {
+    internal var nullTip = "Log with null object" //为空时提示信息
+        private set
+    internal var tagDefault = "Jlog" //默认标签
+        private set
+    internal var tag: String? = null  //标签
+        private set
+    internal var isShowLog = false //是否显示log
+        private set
+    internal var isWrite = false //是否写入文件夹
+        private set
+    internal var writeRootPath = "" //写入文件夹根目录
+        private set
+    internal var isShowWrite = false //是否显示log的时候也写入文件夹
+        private set
+
+    fun setNullTip(nullTip: String): LogConfig {
+        this.nullTip = nullTip
+        return this
+    }
+
+    fun setTagDefault(tagDefault: String): LogConfig {
+        this.tagDefault = tagDefault
+        return this
+    }
+
+    fun setTag(mTag: String?): LogConfig {
+        tag = mTag
+        Jlog.mIsGlobalTagEmpty = TextUtils.isEmpty(mTag)
+        return this
+    }
+
+    fun setShowLog(showLog: Boolean): LogConfig {
+        isShowLog = showLog
+        return this
+    }
+
+    fun setWrite(write: Boolean): LogConfig {
+        isWrite = write
+        return this
+    }
+
+    fun setWriteRootPath(writeRootPath: String): LogConfig {
+        this.writeRootPath = writeRootPath
+        return this
+    }
+
+    fun setShowWrite(showWrite: Boolean): LogConfig {
+        isShowWrite = showWrite
+        return this
+    }
+}

+ 11 - 0
loglib-kt/src/main/java/com/benyanyi/loglib/LogType.kt

@@ -0,0 +1,11 @@
+package com.benyanyi.loglib
+
+/**
+ * @author Administrator
+ * @date 2021/12/14 14:00
+ * @email ben@yanyi.red
+ * @overview
+ */
+internal enum class LogType {
+    V, D, I, W, E, A, JSON, XML
+}

+ 51 - 0
loglib-kt/src/main/java/com/benyanyi/loglib/LogUtil.kt

@@ -0,0 +1,51 @@
+package com.benyanyi.loglib
+
+import com.benyanyi.loglib.BaseLog.writeLog
+import android.text.TextUtils
+import android.util.Log
+
+/**
+ * @author myLove
+ * @time 2017/10/31 10:43
+ * @e-mail ben@yanyi.red
+ * @overview
+ */
+internal object LogUtil {
+    fun isEmpty(line: String): Boolean {
+        return TextUtils.isEmpty(line) || "\n" == line || "\t" == line || TextUtils.isEmpty(line.trim { it <= ' ' })
+    }
+
+    fun printLine(tag: String, isTop: Boolean) {
+        if (isTop) {
+            Log.d(
+                tag,
+                "╔═══════════════════════════════════════════════════════════════════════════════════════"
+            )
+            if (!Jlog.mConfig.isWrite) {
+                return
+            }
+            if (!Jlog.mConfig.isShowWrite && Jlog.mConfig.isShowLog) {
+                return
+            }
+            writeLog(
+                tag,
+                "╔═══════════════════════════════════════════════════════════════════════════════════════"
+            )
+        } else {
+            Log.d(
+                tag,
+                "╚═══════════════════════════════════════════════════════════════════════════════════════"
+            )
+            if (!Jlog.mConfig.isWrite) {
+                return
+            }
+            if (!Jlog.mConfig.isShowWrite && Jlog.mConfig.isShowLog) {
+                return
+            }
+            writeLog(
+                tag,
+                "╚═══════════════════════════════════════════════════════════════════════════════════════"
+            )
+        }
+    }
+}

+ 62 - 0
loglib-kt/src/main/java/com/benyanyi/loglib/XmlLog.kt

@@ -0,0 +1,62 @@
+package com.benyanyi.loglib
+
+import android.util.Log
+import java.io.StringReader
+import java.io.StringWriter
+import java.lang.Exception
+import javax.xml.transform.OutputKeys
+import javax.xml.transform.Source
+import javax.xml.transform.TransformerFactory
+import javax.xml.transform.stream.StreamResult
+import javax.xml.transform.stream.StreamSource
+
+/**
+ * @author myLove
+ * @time 2017/10/31 10:44
+ * @e-mail ben@yanyi.red
+ * @overview
+ */
+internal object XmlLog {
+    fun printXml(tag: String, xml: String?, headString: String) {
+        var msg = xml
+        if (msg != null) {
+            msg = formatXML(msg)
+            msg = """
+                $headString
+                $msg
+                """.trimIndent()
+        } else {
+            msg = headString + Jlog.mConfig.nullTip
+        }
+        LogUtil.printLine(tag, true)
+        val lines = msg.split(Jlog.LINE_SEPARATOR!!.toRegex()).toTypedArray()
+        for (line in lines) {
+            if (!LogUtil.isEmpty(line)) {
+                Log.d(tag, "║ $line")
+                if (!Jlog.mConfig.isWrite) {
+                    return
+                }
+                if (!Jlog.mConfig.isShowWrite && Jlog.mConfig.isShowLog) {
+                    return
+                }
+                BaseLog.writeLog(tag, "║ $line")
+            }
+        }
+        LogUtil.printLine(tag, false)
+    }
+
+    private fun formatXML(inputXML: String): String {
+        return try {
+            val xmlInput: Source = StreamSource(StringReader(inputXML))
+            val xmlOutput = StreamResult(StringWriter())
+            val transformer = TransformerFactory.newInstance().newTransformer()
+            transformer.setOutputProperty(OutputKeys.INDENT, "yes")
+            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2")
+            transformer.transform(xmlInput, xmlOutput)
+            xmlOutput.writer.toString().replaceFirst(">".toRegex(), ">\n")
+        } catch (e: Exception) {
+            e.printStackTrace()
+            inputXML
+        }
+    }
+}

+ 17 - 0
loglib-kt/src/test/java/com/kth/loglib_kt/ExampleUnitTest.kt

@@ -0,0 +1,17 @@
+package com.kth.loglib_kt
+
+import org.junit.Test
+
+import org.junit.Assert.*
+
+/**
+ * Example local unit test, which will execute on the development machine (host).
+ *
+ * See [testing documentation](http://d.android.com/tools/testing).
+ */
+class ExampleUnitTest {
+    @Test
+    fun addition_isCorrect() {
+        assertEquals(4, 2 + 2)
+    }
+}

+ 0 - 5
loglib/build.gradle

@@ -1,12 +1,9 @@
 apply plugin: 'com.android.library'
-apply plugin: 'kotlin-android'
-//apply plugin: 'com.github.dcendents.android-maven'
 
 android {
     compileSdkVersion 29
 
 
-
     defaultConfig {
         minSdkVersion 14
         targetSdkVersion 29
@@ -33,8 +30,6 @@ dependencies {
     testImplementation 'junit:junit:4.13'
     androidTestImplementation 'androidx.test.ext:junit:1.1.2'
     androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
-    implementation "androidx.core:core-ktx:1.3.2"
-    implementation "org.jetbrains.kotlin:kotlin-stdlib:1.5.30"
 }
 apply from: 'bintrayUpload.gradle'
 repositories {

+ 34 - 29
loglib/src/main/java/com/benyanyi/loglib/BaseLog.java

@@ -19,7 +19,7 @@ import java.util.Locale;
 /**
  * @author myLove
  * @time 2017/10/31 10:41
- * @e-mail mylove.520.y@gmail.com
+ * @e-mail ben@yanyi.red
  * @overview
  */
 
@@ -28,7 +28,6 @@ class BaseLog {
     private static final int MAX_LENGTH = 4000;
 
     static void printDefault(LogType type, String tag, String msg) {
-
         int index = 0;
         int length = msg.length();
         int countOfSub = length / MAX_LENGTH;
@@ -46,7 +45,7 @@ class BaseLog {
     }
 
     private static void printSub(LogType type, String tag, String sub) {
-        if (Jlog.IS_SHOW_LOG || Jlog.IS_INIT) {
+        if (Jlog.mConfig.isShowLog() || Jlog.IS_INIT) {
             switch (type) {
                 case V:
                     Log.v(tag, sub);
@@ -68,9 +67,13 @@ class BaseLog {
                     break;
             }
         }
-        if (!Jlog.IS_SHOW_LOG && Jlog.IS_WRITE) {
-            writeLog(tag, sub);
+        if (!Jlog.mConfig.isWrite()) {
+            return;
+        }
+        if (!Jlog.mConfig.isShowWrite() && Jlog.mConfig.isShowLog()) {
+            return;
         }
+        writeLog(tag, sub);
     }
 
     /**
@@ -93,20 +96,25 @@ class BaseLog {
     /**
      * 记录日志
      */
-    private static void writeLog(String tag, String exceptionDescription) {
+    static void writeLog(String tag, String exceptionDescription) {
         try {
-            Application application = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null, (Object[]) null);
-            assert application != null;
-            String packageName = application.getPackageName();
-            if (exceptionDescription == null || TextUtils.isEmpty(packageName)) {
-                return;
-            }
-            String fileName = packageName;
-            String[] split = packageName.split("\\.");
-            if (split != null) {
-                fileName = split[split.length - 1];
+            String ROOT_PATH;
+            if (TextUtils.isEmpty(Jlog.mConfig.getWriteRootPath()) || Jlog.mConfig.getWriteRootPath().equalsIgnoreCase("null")) {
+                Application application = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null, (Object[]) null);
+                assert application != null;
+                String packageName = application.getPackageName();
+                if (exceptionDescription == null || TextUtils.isEmpty(packageName)) {
+                    return;
+                }
+                String fileName = packageName;
+                String[] split = packageName.split("\\.");
+                if (split != null) {
+                    fileName = split[split.length - 1];
+                }
+                ROOT_PATH = Environment.getExternalStorageDirectory() + "/" + fileName + "/";
+            } else {
+                ROOT_PATH = Jlog.mConfig.getWriteRootPath();
             }
-            String ROOT_PATH = Environment.getExternalStorageDirectory() + "/" + fileName + "/";
             File rootFile = new File(ROOT_PATH);
             try {
                 if (!rootFile.exists()) {
@@ -127,30 +135,27 @@ class BaseLog {
             //获取当前时间
             Date date = new Date(System.currentTimeMillis());
             File logFile = new File(logPath + "/" + simpleDateFormat.format(date) + ".txt");
-//            long size = getFileSizes(logFile);
-//            if (size > 1024 * 1024 * 2) {
-//                logFile.delete();
-//            }
             try {
                 if (logPath.exists() && !logFile.exists()) {
                     logFile.createNewFile();
                 }
             } catch (Exception e) {
-//                e.printStackTrace();
             }
-            //String size=FileUtils.getFileSize(logFile);
-            //if(){};
+            FileWriter fw = null;
             if (logFile.exists()) {
                 try {
-                    FileWriter fw = new FileWriter(logFile, true);
+                    fw = new FileWriter(logFile, true);
                     if (TextUtils.isEmpty(tag)) {
-                        fw.write(getTimeString() + "\r\n\t\t" + exceptionDescription + "\r\n");
+                        fw.write(getTimeString() + "\t\t" + exceptionDescription + "\r\n");
                     } else {
-                        fw.write(getTimeString() + "\r\n\t\t" + tag + "\t\t" + exceptionDescription + "\r\n");
+                        fw.write(getTimeString() + "\t\t" + tag + "\t\t" + exceptionDescription + "\r\n");
                     }
-                    fw.close();
                 } catch (Exception e) {
                     e.printStackTrace();
+                } finally {
+                    if (fw != null) {
+                        fw.close();
+                    }
                 }
             }
         } catch (Exception e) {
@@ -189,7 +194,7 @@ class BaseLog {
      *
      * @return str
      */
-    private static String getTimeString() {
+    static String getTimeString() {
         SimpleDateFormat dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
         return dateStr.format(new Date());
     }

+ 1 - 1
loglib/src/main/java/com/benyanyi/loglib/FileLog.java

@@ -17,7 +17,7 @@ import java.util.Random;
 /**
  * @author myLove
  * @time 2017/10/31 10:40
- * @e-mail mylove.520.y@gmail.com
+ * @e-mail ben@yanyi.red
  * @overview
  */
 

+ 45 - 57
loglib/src/main/java/com/benyanyi/loglib/Jlog.java

@@ -1,12 +1,8 @@
 package com.benyanyi.loglib;
 
-import android.annotation.SuppressLint;
-import android.app.Application;
-import android.content.pm.ApplicationInfo;
 import android.text.TextUtils;
 
 import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
 
 import java.io.File;
 import java.io.PrintWriter;
@@ -15,46 +11,32 @@ import java.io.StringWriter;
 /**
  * @author myLove
  * @time 2017/10/31 10:39
- * @e-mail mylove.520.y@gmail.com
+ * @e-mail ben@yanyi.red
  * @overview
  */
 
 public final class Jlog {
     static final String LINE_SEPARATOR = System.getProperty("line.separator");
-    static final String NULL_TIPS = "Log with null object";
 
     private static final String DEFAULT_MESSAGE = "********";
     private static final String PARAM = "Param";
     private static final String NULL = "null";
-    private static final String TAG_DEFAULT = "Jlog";
 
     static final int JSON_INDENT = 4;
 
-    private static String mGlobalTag;
-    private static boolean mIsGlobalTagEmpty = true;
-    static boolean IS_SHOW_LOG = false;
-    static boolean IS_WRITE = false;
+    static boolean mIsGlobalTagEmpty = true;
     static boolean IS_INIT = true;
+    static LogConfig mConfig = new LogConfig();
 
-    public static void init(boolean isShowLog) {
-        IS_INIT = isShowLog;
-        IS_SHOW_LOG = isShowLog;
+    public static LogConfig init() {
+        return mConfig;
     }
 
-    public static void init(boolean isShowLog, @Nullable String tag) {
-        init(isShowLog);
-        mGlobalTag = tag;
-        mIsGlobalTagEmpty = TextUtils.isEmpty(mGlobalTag);
-    }
-
-    public static void init(boolean isShowLog, boolean isWrite) {
-        init(isShowLog);
-        IS_WRITE = isWrite;
-    }
-
-    public static void init(boolean isShowLog, boolean isWrite, @Nullable String tag) {
-        init(isShowLog, tag);
-        IS_WRITE = isWrite;
+    public static void init(LogConfig config) {
+        if (config == null) {
+            return;
+        }
+        mConfig = config;
     }
 
     public static void v() {
@@ -178,22 +160,22 @@ public final class Jlog {
     }
 
     public static void errorWriteFile(Throwable throwable) {
-        if (IS_WRITE) {
+        if (mConfig.isWrite()) {
             BaseLog.writeError(null, throwable);
         }
     }
 
     public static void errorWriteFile(String tag, Throwable throwable) {
-        if (IS_WRITE) {
+        if (mConfig.isWrite()) {
             BaseLog.writeError(tag, throwable);
         }
     }
 
     private static void printStackTrace() {
-        if (!IS_INIT && !IS_WRITE) {
+        if (!IS_INIT && !mConfig.isWrite()) {
             return;
         }
-        if (!IS_SHOW_LOG && isApkInDebug() && !IS_WRITE) {
+        if (!mConfig.isShowLog() && isApkInDebug() && !mConfig.isWrite()) {
             return;
         }
 
@@ -224,10 +206,10 @@ public final class Jlog {
     }
 
     private static void printLog(LogType type, Object tagStr, Object... objects) {
-        if (!IS_INIT && !IS_WRITE) {
+        if (!IS_INIT && !mConfig.isWrite()) {
             return;
         }
-        if (!IS_SHOW_LOG && isApkInDebug() && !IS_WRITE) {
+        if (!mConfig.isShowLog() && isApkInDebug() && !mConfig.isWrite()) {
             return;
         }
         String[] contents = wrapperContent(tagStr, objects);
@@ -258,7 +240,7 @@ public final class Jlog {
     }
 
     private static void printDebug(Object tagStr, Object... objects) {
-        if (!IS_INIT || !IS_SHOW_LOG) {
+        if (!IS_INIT || !mConfig.isWrite()) {
             return;
         }
         String[] contents = wrapperContent(tagStr, objects);
@@ -272,10 +254,10 @@ public final class Jlog {
     }
 
     private static void printFile(Object tagStr, File targetDirectory, String fileName, Object objectMsg) {
-        if (!IS_INIT && !IS_WRITE) {
+        if (!IS_INIT && !mConfig.isWrite()) {
             return;
         }
-        if (!IS_SHOW_LOG && isApkInDebug()) {
+        if (!mConfig.isShowLog() && isApkInDebug() && !mConfig.isWrite()) {
             return;
         }
         String[] contents = wrapperContent(tagStr, objectMsg);
@@ -321,12 +303,12 @@ public final class Jlog {
         String tag = (tagStr == null ? fileName : tagStr).toString();
 
         if (mIsGlobalTagEmpty && TextUtils.isEmpty(tag)) {
-            tag = TAG_DEFAULT;
+            tag = mConfig.getTagDefault();
         } else if (!mIsGlobalTagEmpty) {
-            tag = mGlobalTag;
+            tag = mConfig.getTagDefault();
         }
 
-        String msg = (objects == null) ? NULL_TIPS : getObjectsString(objects);
+        String msg = (objects == null) ? mConfig.getNullTip() : getObjectsString(objects);
         String headString = "[ (" + fileName + ":" + lineNumber + ")#" + methodName + " ] ";
 
         return new String[]{tag, msg, headString};
@@ -342,7 +324,7 @@ public final class Jlog {
                 if (object == null) {
                     stringBuilder.append(PARAM).append("[").append(i).append("]").append(" = ").append(NULL).append("\n");
                 } else {
-                    stringBuilder.append(PARAM).append("[").append(i).append("]").append(" = ").append(object.toString()).append("\n");
+                    stringBuilder.append(PARAM).append("[").append(i).append("]").append(" = ").append(object).append("\n");
                 }
             }
             return stringBuilder.toString();
@@ -353,21 +335,27 @@ public final class Jlog {
     }
 
     private static boolean isApkInDebug() {
-        try {
-            @SuppressLint("PrivateApi")
-            Class<?> activityThread = Class.forName("android.app.ActivityThread");
-            Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
-            Object app = activityThread.getMethod("getApplication").invoke(thread);
-            Application application;
-            if (app == null) {
-                application = null;
-            } else {
-                application = (Application) app;
-            }
-            ApplicationInfo info = application.getApplicationInfo();
-            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0;
-        } catch (Exception e) {
-            return false;
-        }
+        return BuildConfig.DEBUG;
+//        try {
+//            @SuppressLint("PrivateApi")
+//            Class<?> activityThread = Class.forName("android.app.ActivityThread");
+//            Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
+//            Object app = activityThread.getMethod("getApplication").invoke(thread);
+//            Application application;
+//            if (app == null) {
+//                application = null;
+//            } else {
+//                application = (Application) app;
+//            }
+//            ApplicationInfo info = application.getApplicationInfo();
+//            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0;
+//        } catch (Exception e) {
+//            return false;
+//        }
+    }
+
+    void aaa(String... str){
+
     }
+
 }

+ 8 - 2
loglib/src/main/java/com/benyanyi/loglib/JsonLog.java

@@ -9,7 +9,7 @@ import org.json.JSONObject;
 /**
  * @author myLove
  * @time 2017/10/31 10:42
- * @e-mail mylove.520.y@gmail.com
+ * @e-mail ben@yanyi.red
  * @overview
  */
 
@@ -32,12 +32,18 @@ class JsonLog {
         } catch (JSONException e) {
             message = msg;
         }
-
         LogUtil.printLine(tag, true);
         message = headString + Jlog.LINE_SEPARATOR + message;
         String[] lines = message.split(Jlog.LINE_SEPARATOR);
         for (String line : lines) {
             Log.d(tag, "║ " + line);
+            if (!Jlog.mConfig.isWrite()) {
+                return;
+            }
+            if (!Jlog.mConfig.isShowWrite() && Jlog.mConfig.isShowLog()) {
+                return;
+            }
+            BaseLog.writeLog(tag, "║ " + line);
         }
         LogUtil.printLine(tag, false);
     }

+ 84 - 0
loglib/src/main/java/com/benyanyi/loglib/LogConfig.java

@@ -0,0 +1,84 @@
+package com.benyanyi.loglib;
+
+import android.text.TextUtils;
+
+/**
+ * @author myLove
+ * @date 2022/11/30 13:21
+ * @email ben@yanyi.red
+ * @overview
+ */
+public class LogConfig {
+    private String nullTip = "Log with null object";//为空时提示信息
+    private String tagDefault = "Jlog";//默认标签
+    private String mTag;//标签
+    private boolean isShowLog = false;//是否显示log
+    private boolean isWrite = false;//是否写入文件夹
+    private String writeRootPath = "";//写入文件夹根目录
+    private boolean isShowWrite = false;//是否显示log的时候也写入文件夹
+
+    public LogConfig setNullTip(String nullTip) {
+        this.nullTip = nullTip;
+        return this;
+    }
+
+    public LogConfig setTagDefault(String tagDefault) {
+        this.tagDefault = tagDefault;
+        return this;
+    }
+
+    public LogConfig setTag(String mTag) {
+        this.mTag = mTag;
+        Jlog.mIsGlobalTagEmpty = TextUtils.isEmpty(mTag);
+        return this;
+    }
+
+    public LogConfig setShowLog(boolean showLog) {
+        this.isShowLog = showLog;
+        return this;
+    }
+
+    public LogConfig setWrite(boolean write) {
+        this.isWrite = write;
+        return this;
+    }
+
+    public LogConfig setWriteRootPath(String writeRootPath) {
+        this.writeRootPath = writeRootPath;
+        return this;
+    }
+
+    public LogConfig setShowWrite(boolean showWrite) {
+        this.isShowWrite = showWrite;
+        return this;
+    }
+
+    String getNullTip() {
+        return nullTip;
+    }
+
+    String getTagDefault() {
+        return tagDefault;
+    }
+
+    String getTag() {
+        return mTag;
+    }
+
+    boolean isShowLog() {
+        return isShowLog;
+    }
+
+    boolean isWrite() {
+        return isWrite;
+    }
+
+    String getWriteRootPath() {
+        return writeRootPath;
+    }
+
+    boolean isShowWrite() {
+        return isShowWrite;
+    }
+
+}

+ 15 - 1
loglib/src/main/java/com/benyanyi/loglib/LogUtil.java

@@ -6,7 +6,7 @@ import android.util.Log;
 /**
  * @author myLove
  * @time 2017/10/31 10:43
- * @e-mail mylove.520.y@gmail.com
+ * @e-mail ben@yanyi.red
  * @overview
  */
 
@@ -18,8 +18,22 @@ class LogUtil {
     static void printLine(String tag, boolean isTop) {
         if (isTop) {
             Log.d(tag, "╔═══════════════════════════════════════════════════════════════════════════════════════");
+            if (!Jlog.mConfig.isWrite()) {
+                return;
+            }
+            if (!Jlog.mConfig.isShowWrite() && Jlog.mConfig.isShowLog()) {
+                return;
+            }
+            BaseLog.writeLog(tag, "╔═══════════════════════════════════════════════════════════════════════════════════════");
         } else {
             Log.d(tag, "╚═══════════════════════════════════════════════════════════════════════════════════════");
+            if (!Jlog.mConfig.isWrite()) {
+                return;
+            }
+            if (!Jlog.mConfig.isShowWrite() && Jlog.mConfig.isShowLog()) {
+                return;
+            }
+            BaseLog.writeLog(tag, "╚═══════════════════════════════════════════════════════════════════════════════════════");
         }
     }
 }

+ 9 - 3
loglib/src/main/java/com/benyanyi/loglib/XmlLog.java

@@ -15,10 +15,9 @@ import javax.xml.transform.stream.StreamSource;
 /**
  * @author myLove
  * @time 2017/10/31 10:44
- * @e-mail mylove.520.y@gmail.com
+ * @e-mail ben@yanyi.red
  * @overview
  */
-
 class XmlLog {
     static void printXml(String tag, String xml, String headString) {
         String msg = xml;
@@ -26,13 +25,20 @@ class XmlLog {
             msg = formatXML(msg);
             msg = headString + "\n" + msg;
         } else {
-            msg = headString + Jlog.NULL_TIPS;
+            msg = headString + Jlog.mConfig.getNullTip();
         }
         LogUtil.printLine(tag, true);
         String[] lines = msg.split(Jlog.LINE_SEPARATOR);
         for (String line : lines) {
             if (!LogUtil.isEmpty(line)) {
                 Log.d(tag, "║ " + line);
+                if (!Jlog.mConfig.isWrite()) {
+                    return;
+                }
+                if (!Jlog.mConfig.isShowWrite() && Jlog.mConfig.isShowLog()) {
+                    return;
+                }
+                BaseLog.writeLog(tag, "║ " + line);
             }
         }
         LogUtil.printLine(tag, false);

+ 1 - 0
settings.gradle

@@ -1 +1,2 @@
 include ':app', ':loglib'
+include ':loglib-kt'