fun appErrorLog() {
//主线程异常拦截
Handler(Looper.getMainLooper()).post {
while (true) {
try {
Looper.loop()
} catch (e: Throwable) {
LogUtil.e("MainThreadExceptionInterception", errorToString(e))
}
}
}
//子线程异常拦截
Thread.setDefaultUncaughtExceptionHandler { t: Thread, e: Throwable ->
LogUtil.e("SubThreadExceptionInterception", errorToString(e))
}
}
fun errorToString(e: Throwable): String {
val sb = StringBuilder()
var i = 0
sb.appendLine("Error:Thread " + Thread.currentThread().name + " throws an exception with message")
try {
while (true) {
val error = error(e, sb, i)
i++
if (error?.cause == null) {
return sb.toString()
}
}
} catch (e: Exception) {
sb.append(e.toString())
return sb.toString()
}
}
private fun error(e: Throwable, sb: StringBuilder, i: Int): Throwable? {
sb.append("cause ")
sb.appendLine(i)
sb.appendLine(e)
sb.append("cause.stackTrace ")
sb.appendLine(i)
sb.appendLine(e.stackTrace.joinToString("\n"))
return e.cause
}
public class LogUtil {
public static void d(String tag, Object... o) {
if (Configs.isdebug) {
print_d(conversion(tag, o));
}
}
public static void e(String tag, Object... o) {
if (Configs.isdebug) {
print_e(conversion(tag, o));
}
}
private static String conversion(String tag, Object... o) {
StringBuilder builder = new StringBuilder();
builder.append(" \n*************************** start ***********************************");
if (o.length == 0) {
builder.append("\ntag -->").append(tag).append("\n");
} else {
builder.append("\ntag -->").append(tag).append("\nvalue -->");
for (Object i : o) {
if (i != null) {
builder.append(i).append("\n");
}
}
}
builder.append("*************************** end ***********************************");
return builder.toString();
}
private static void print_d(String o) {
Log.d("LogUtil", o);
}
private static void print_e(String o) {
Log.e("LogUtil", o);
}
}