Browse Source

网络异常堆栈使用 NetConfig.logTag 作为标签, 使用debug日志类型输出

drake 3 years ago
parent
commit
97c31dddde

+ 1 - 1
docs/callback.md

@@ -63,7 +63,7 @@ Net.post("api").onResult<String> {
 
     exceptionOrNull()?.apply {
         Log.d("日志", "请求失败")
-        printStackTrace() // 如果发生错误就不为Null
+        Net.printStackTrace(this) // 如果发生错误就不为Null
     }
 
     Log.d("日志", "完成请求")

+ 38 - 2
net/src/main/java/com/drake/net/Net.kt

@@ -18,12 +18,14 @@
 
 package com.drake.net
 
+import android.util.Log
 import com.drake.net.interfaces.ProgressListener
 import com.drake.net.request.*
 import com.drake.net.tag.NetLabel
 import okhttp3.Request
-import java.util.*
-import kotlin.collections.ArrayList
+import java.io.PrintWriter
+import java.io.StringWriter
+import java.net.UnknownHostException
 
 object Net {
 
@@ -257,4 +259,38 @@ object Net {
         return requests
     }
     //</editor-fold>
+
+    /**
+     * 输出异常日志
+     * @see NetConfig.logTag
+     */
+    fun printStackTrace(t: Throwable) {
+        if (NetConfig.logEnabled) {
+            Log.d(NetConfig.logTag, getStackTraceString(t))
+        }
+    }
+
+    /**
+     * 返回异常堆栈日志字符串
+     * 如果tr为null则返回空字符串
+     */
+    private fun getStackTraceString(tr: Throwable?): String {
+        if (tr == null) {
+            return ""
+        }
+        // This is to reduce the amount of log spew that apps do in the non-error
+        // condition of the network being unavailable.
+        var t = tr
+        while (t != null) {
+            if (t is UnknownHostException) {
+                return t.message ?: ""
+            }
+            t = t.cause
+        }
+        val sw = StringWriter()
+        val pw = PrintWriter(sw)
+        tr.printStackTrace(pw)
+        pw.flush()
+        return sw.toString()
+    }
 }

+ 3 - 0
net/src/main/java/com/drake/net/NetConfig.kt

@@ -70,6 +70,9 @@ object NetConfig {
     /** 是否启用日志 */
     var logEnabled = true
 
+    /** 网络异常日志的标签 */
+    var logTag = "NET-LOG"
+
     /** 运行中的请求 */
     var runningCalls: ConcurrentLinkedQueue<WeakReference<Call>> = ConcurrentLinkedQueue()
         private set

+ 0 - 3
net/src/main/java/com/drake/net/exception/HttpFailureException.kt

@@ -4,9 +4,6 @@ import okhttp3.Request
 
 /**
  * 实现该接口表示Http请求失败
- * @see NetUnknownHostException
- * @see NetConnectException
- * @see NetSocketTimeoutException
  */
 open class HttpFailureException(
     request: Request,

+ 1 - 1
net/src/main/java/com/drake/net/interceptor/NetOkHttpInterceptor.kt

@@ -33,7 +33,7 @@ object NetOkHttpInterceptor : Interceptor {
         } catch (e: ConnectException) {
             throw NetConnectException(request, cause = e)
         } catch (e: UnknownHostException) {
-            throw NetUnknownHostException(request, cause = e)
+            throw NetUnknownHostException(request, message = e.message)
         } catch (e: Throwable) {
             throw HttpFailureException(request, cause = e)
         }

+ 3 - 2
net/src/main/java/com/drake/net/interfaces/NetErrorHandler.kt

@@ -1,6 +1,7 @@
 package com.drake.net.interfaces
 
 import android.view.View
+import com.drake.net.Net
 import com.drake.net.NetConfig
 import com.drake.net.R
 import com.drake.net.exception.*
@@ -37,7 +38,7 @@ interface NetErrorHandler {
             else -> NetConfig.app.getString(R.string.net_other_error)
         }
 
-        if (NetConfig.logEnabled) e.printStackTrace()
+        Net.printStackTrace(e)
         TipUtils.toast(message)
     }
 
@@ -53,7 +54,7 @@ interface NetErrorHandler {
             is RequestParamsException,
             is ResponseException,
             is NullPointerException -> onError(e)
-            else -> if (NetConfig.logEnabled) e.printStackTrace()
+            else -> Net.printStackTrace(e)
         }
     }
 }

+ 2 - 1
net/src/main/java/com/drake/net/log/LogRecorder.kt

@@ -3,6 +3,7 @@ package com.drake.net.log
 import android.annotation.SuppressLint
 import android.os.*
 import android.util.Log
+import com.drake.net.Net
 import com.drake.net.log.LogRecorder.enabled
 import java.text.DateFormat
 import java.text.SimpleDateFormat
@@ -191,7 +192,7 @@ object LogRecorder {
                     try {
                         Thread.sleep(5L)
                     } catch (e: InterruptedException) {
-                        e.printStackTrace()
+                        Net.printStackTrace(e)
                     }
                 }
                 val data = bundle.getString(KEY_VALUE) ?: "null"

+ 2 - 2
net/src/main/java/com/drake/net/scope/AndroidScope.kt

@@ -19,7 +19,7 @@ package com.drake.net.scope
 import androidx.lifecycle.Lifecycle
 import androidx.lifecycle.LifecycleEventObserver
 import androidx.lifecycle.LifecycleOwner
-import com.drake.net.NetConfig
+import com.drake.net.Net
 import kotlinx.coroutines.*
 import java.io.Closeable
 import kotlin.coroutines.CoroutineContext
@@ -96,7 +96,7 @@ open class AndroidScope(
      * 错误处理
      */
     open fun handleError(e: Throwable) {
-        if (NetConfig.logEnabled) e.printStackTrace()
+        Net.printStackTrace(e)
     }
 
     open fun cancel(cause: CancellationException? = null) {

+ 2 - 3
net/src/main/java/com/drake/net/utils/Fastest.kt

@@ -17,7 +17,6 @@
 package com.drake.net.utils
 
 import com.drake.net.Net
-import com.drake.net.NetConfig
 import com.drake.net.transform.DeferredTransform
 import kotlinx.coroutines.*
 import kotlinx.coroutines.sync.Mutex
@@ -56,7 +55,7 @@ suspend fun <T> CoroutineScope.fastest(
                 val allFail = listDeferred.all { it.isCancelled }
                 if (allFail) deferred.completeExceptionally(e) else {
                     if (e !is CancellationException) {
-                        if (NetConfig.logEnabled) e.printStackTrace()
+                        Net.printStackTrace(e)
                     }
                 }
             }
@@ -103,7 +102,7 @@ suspend fun <T, R> CoroutineScope.fastest(
                 val allFail = listDeferred.all { it.deferred.isCancelled }
                 if (allFail) deferred.completeExceptionally(e) else {
                     if (e !is CancellationException) {
-                        if (NetConfig.logEnabled) e.printStackTrace()
+                        Net.printStackTrace(e)
                     }
                 }
             }

+ 2 - 1
net/src/main/java/com/drake/net/utils/FileUtils.kt

@@ -5,6 +5,7 @@ import android.net.Uri
 import android.os.Build
 import android.webkit.MimeTypeMap
 import androidx.core.content.FileProvider
+import com.drake.net.Net
 import com.drake.net.NetConfig
 import okhttp3.MediaType
 import okhttp3.MediaType.Companion.toMediaTypeOrNull
@@ -34,7 +35,7 @@ fun File.md5(): String? {
         for (b in md5) stringBuilder.append(String.format("%02X", b))
         return stringBuilder.toString().toLowerCase(Locale.ROOT)
     } catch (e: IOException) {
-        e.printStackTrace()
+        Net.printStackTrace(e)
     }
     return null
 }

+ 4 - 3
net/src/main/java/com/drake/net/utils/Https.kt

@@ -15,6 +15,7 @@
  */
 package com.drake.net.utils
 
+import com.drake.net.Net
 import java.io.IOException
 import java.io.InputStream
 import java.security.KeyStore
@@ -61,7 +62,7 @@ internal fun prepareKeyManager(bksFile: InputStream?, password: String?): Array<
         kmf.init(clientKeyStore, password.toCharArray())
         return kmf.keyManagers
     } catch (e: Exception) {
-        e.printStackTrace()
+        Net.printStackTrace(e)
     }
     return null
 }
@@ -82,7 +83,7 @@ internal fun prepareTrustManager(vararg certificates: InputStream?): Array<Trust
             try {
                 certStream?.close()
             } catch (e: IOException) {
-                e.printStackTrace()
+                Net.printStackTrace(e)
             }
         }
         // 我们创建一个默认类型的TrustManagerFactory
@@ -92,7 +93,7 @@ internal fun prepareTrustManager(vararg certificates: InputStream?): Array<Trust
         // 通过tmf获取TrustManager数组,TrustManager也会信任keyStore中的证书
         return tmf.trustManagers
     } catch (e: Exception) {
-        e.printStackTrace()
+        Net.printStackTrace(e)
     }
     return null
 }

+ 1 - 1
sample/src/main/java/com/drake/net/sample/ui/fragment/CallbackRequestFragment.kt

@@ -43,7 +43,7 @@ class CallbackRequestFragment :
 
             exceptionOrNull()?.apply {
                 Log.d("日志", "请求失败")
-                printStackTrace() // 如果发生错误就不为Null
+                Net.printStackTrace(this) // 如果发生错误就不为Null
             }
 
             Log.d("日志", "完成请求")