您的位置:首页 > 移动开发 > Android开发

Android中全局异常捕获以及动态logcat打印。方便上线项目分析

2016-11-30 16:21 543 查看
很多时候我们会出现出现了一个问题,但是我们自己并没有日志的情况。这个时候怎么办呢。其实在我们的软件中集成一些日志上报的功能有时候是有需要的。那么问题来了:我们该在自己代码中动态捕获自己应用的日志,以及错误信息呢。其实android 给出了两种:

1.运行时异常捕获:

这个很容易明白,就是在程序正常运行中,如果程序出现了全局的异常,那么我们就捕获异常,并且把异常信息给收集处理。比如我们可以通过指定的后台接口进行上传,这样就方便我们后期对这些异常的处理。

那我们最关心的是如何处理呢:先上代码。

public class CrashHandler implements Thread.UncaughtExceptionHandler {
public static final String TAG = "CrashHandler";

// 系统默认的UncaughtException处理类
private Thread.UncaughtExceptionHandler mDefaultHandler;
// CrashHandler实例
private static CrashHandler INSTANCE = new CrashHandler();
// 程序的Context对象
private Context mContext;
// 用来存储设备信息和异常信息
private Map<String, String> infos = new HashMap<String, String>();

// 用于格式化日期,作为日志文件名的一部分
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
private String nameString="/logcat";

/** 保证只有一个CrashHandler实例 */
private CrashHandler() {
}

/** 获取CrashHandler实例 ,单例模式 */
public static CrashHandler getInstance() {
return INSTANCE;
}

/**
* 初始化
*
* @param context
*/
public void init(Context context) {
mContext = context;
// 获取系统默认的UncaughtException处理器
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
// 设置该CrashHandler为程序的默认处理器
Thread.setDefaultUncaughtExceptionHandler(this);
}

/**
* 当UncaughtException发生时会转入该函数来处理
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {

if (!handleException(ex) && mDefaultHandler != null) {
// 如果用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(TAG, "error : ", e);
}
// 退出程序
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
}

/**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
*
* @param ex
* @return true:如果处理了该异常信息;否则返回false.
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
//       WonderMapApplication.getInstance().getSpUtil().setCrashLog(true);// 每次进入应用检查,是否有log,有则上传
// 使用Toast来显示异常信息
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(mContext, "很抱歉,程序出现异常,正在收集日志,即将退出", Toast.LENGTH_LONG)
.show();
Looper.loop();
}
}.start();
// 收集设备参数信息
collectDeviceInfo(mContext);
// 保存日志文件
//getLog();
String fileName = saveCrashInfo2File(ex);
return true;
}

/**
* 收集设备参数信息
*
* @param ctx
*/
public void collectDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),
PackageManager.GET_ACTIVITIES);
if (pi != null) {
String versionName = pi.versionName == null ? "null"
: pi.versionName;
String versionCode = pi.versionCode + "";
infos.put("versionName", versionName);
infos.put("versionCode", versionCode);
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "an error occured when collect package info", e);
}
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
infos.put(field.getName(), field.get(null).toString());
Log.d(TAG, field.getName() + " : " + field.get(null));
} catch (Exception e) {
Log.e(TAG, "an error occured when collect crash info", e);
}
}
}

/**
* 保存错误信息到文件中
*
* @param ex
* @return 返回文件名称,便于将文件传送到服务器
*/
private String saveCrashInfo2File(Throwable ex) {

StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : infos.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value + "\n");
}

Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
printWriter.close();
String result = writer.toString();
Log.d("########", result);
sb.append(result);
try {
long timestamp = System.currentTimeMillis();
String time = formatter.format(new Date());
String fileName = nameString + "-" + time + "-" + timestamp
+ ".log";
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Log.e("tags",Environment.getExternalStorageDirectory().getAbsolutePath());
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+LogFileDivider.LOG_FILE;
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path + fileName);
fos.write(sb.toString().getBytes());
fos.close();
}
return fileName;
} catch (Exception e) {
Log.e(TAG, "an error occured while writing file...", e);
}
return null;
}
}


代码中有明确的代码注释这边就不过多的解释了。但是主要的核心呢其实就是实现的UncaughtExceptionHandler这个接口。它里面需要重写一个uncaughtException方法,这个方法就是全局异常出现的回调。我们只需要重写它就能拿到其中的错误信息。看下源码:

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);
}


这样我们可以通过自己的处理加上一些类似设备信息呀。然后获取异常中的message 这样异常错误我们就能找到了。很方便上线的错误定位。但是这个异常只针对运行时的,像一些anr问题就没有任何提示,这样就拿不到我们需要的错误信息了。并且其中只包含了异常信息。并没有我们想要的日志。

2.运行logcat动态捕获:

这个效果就能做到我们开发中ide中的logcat异常的效果。其实也是帮助非常大的,因为我们有许多时候是想知道这些日志的。那我们该如何实现呢。

android 权限机制中有一个权限叫:

<uses-permission android:name="android.permission.READ_LOGS" />


这个是读取log的权限。但是我们要怎么读呢。其实就是通过Runtime.getRuntime().exec(command);通过获得运行时环境(也就是java虚拟机)来进入到对应的平台。比如安卓中会到底层的linux系统中,通过shell执行一些command命令。其实我们平时经常会通过adbshell 来调试我们的手机,和这个的原理应该是一样的。在adb shell 中我们会通过adb logcat 来查看android设备上的日志。

adb logcat -s System.out   输出System.out标签的信息
adb logcat -f /sdcard/log.txt   输出到手机文件上,可以使用&后台运行
adb shell ps | grep logcat     查找进程
adb shell ps | findstr "logcat" 查找进程,windows平台命令

adb logcat > log
ctrl C
more log    使用more log 查看日志信息

adb logcat -d -v /sdcard/mylog.txt  日志保存在手机指定位置
adb logcat -v time   查看日志输出时间
adb logcat -v threadtime   日志输出时间和线程信息
adb logcat -v brief        默认的日志格式
adb logcat -v process      进程优先级日志信息
adb logcat -v tag           标签优先级日志信息
adb logcat -v raw          只输出日志不输出其它信息
adb logcat -v time         time格式输出

adb logcat -c               清空
adb logcat -d             缓存输出
adb logcat -t 5          最近5行
adb logcat -g           查看日志缓冲区
adb logcat -b         加载日志缓冲区
adb logcat -B         二进制形式输出日志

adb logcat  *:E    显示Error以上级别日志


一系列的指令的都是可以查看日志的。还可以通过规则进行过滤。

那么安卓中的指令是什么呢:

//打印V级别以上的log包含时间
String cmd="logcat -d -v time -t 1000 *:V"
Runtime.getRuntime().exec(cmd)


这样我们可以对 返回的Process 进行读取

Process process=Runtime.getRuntime().exec(cmd);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String LogStr="";
String line;
while ((line = bufferedReader.readLine()) != null) {
//清理日志,如果你这里做了sout,那么你输出的内容也会被记录,就会出现问题
LogStr=line+"\n"+LogStr;
}


这样我们就能够拿到读取的log 了。 其实和logcat里面的很像,但是会有一些区别。

有了log我们就可以做对应的处理了。也是非常简单。文件保存呀,服务器上传呀等等。

这个logcat github上有个很好的开源项目,有需要可以看下,做了一些封装。地址:

https://github.com/tianzhijiexian/Logcat.git

这样呢两种日志和异常捕获我们都说完了。其实因为第二种捕获logcat 无法实时捕获,到底什么时候捕获呢。这个可以根据自己的需求来定,当然你可以和第一种结合起来使用,就是出现异常的时候我们先捕获全局的log,再做其他的异常处理、这样也能更加有助我们进行分析。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  logcat 异常 adb-shell