APP日志采集的原理及其实现
一.crash产生的原因
当Android设备上的App应用闪退时,操作系统会生成一个crash日志。crash日志上有很多有用的信息,比如每个正在执行线程的完整堆栈跟踪信息和内存映像,这样就能够通过解析这些信息进而定位crash发生时的代码逻辑,从而找到App闪退的原因。
奔溃的原因一般有两种:
- 违反Android系统规则导致的crash(如一次性操作大量的内存)
- App代码逻辑BUG(如空指针)导致的crash
二. crash收集的原理
通常有成熟的商业第三方库能为你手机crash,如国内常用的友盟。他们的原理其实都是去系统产生的crash日志里面抓取出日志,进行了一次提取或封装,然后将封装后的crash文件上传到对应的服务端进行解析处理。然后就可以通过后台去查看相应的日志。
三、Android日志crash采集的具体实现:
Java代码中有一个类Thread.UncaughtExceptionHandler可用于收集导致奔溃,无法处理的异常。
/**
* Implemented by objects that want to handle cases where a thread is being
* terminated by an uncaught exception. Upon such termination, the handler
* is notified of the terminating thread and causal exception. If there is
* no explicit handler set then the thread's group is the default handler.
*/
public static interface UncaughtExceptionHandler {
/**
* The thread is being terminated by an uncaught exception. Further
* exceptions thrown in this method are prevent the remainder of the
* method from executing, but are otherwise ignored.
*
* @param thread
the thread that has an uncaught exception
* @param ex
the exception that was thrown
*/
void uncaughtException(Thread thread,Throwable ex);
}
重写uncaughtException方法,其中ex就包含了所有导致崩溃的堆栈信息,再同时抓取一些相关的设备的版本、IMEI等等信息。持久化成文件(或插入手机的数据库),找时机打包上传(如wifi环境下)到服务器即可。
如果希望方便的阅读日志,则写个网页,将日志呈现在页面中出来。
当然,目前主流都是使用第三方库实现收集日志和查看的功能。
本文介绍了Android应用中crash产生的原因,包括违反系统规则和代码逻辑错误。讲解了crash收集的原理,主要依赖第三方库如友盟从系统日志中抓取并上传。还探讨了Android日志crash采集的实现,通过自定义`UncaughtExceptionHandler`来捕获异常信息,并在合适时机上传到服务器。最后提到,通常使用第三方库来简化日志管理和查看。
1172

被折叠的 条评论
为什么被折叠?



