1.在Application里面初始化

AppCrashHandler.getInstance(this);

2.创建一个类
package com.lvshandian.partylive.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast; /**
* <h3>全局捕获异常</h3> <br>
* 当程序发生Uncaught异常的时候,有该类来接管程序,并记录错误日志
*/
@SuppressLint("SimpleDateFormat")
public class CrashHandler implements UncaughtExceptionHandler { public static String TAG = "MyCrash";
// 系统默认的UncaughtException处理类
private Thread.UncaughtExceptionHandler mDefaultHandler; private static CrashHandler instance = new CrashHandler();
private Context mContext; // 用来存储设备信息和异常信息
private Map<String, String> infos = new HashMap<String, String>(); // 用于格式化日期,作为日志文件名的一部分
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); /**
* 保证只有一个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 {
SystemClock.sleep(3000);
// 退出程序
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; try {
// 使用Toast来显示异常信息
new Thread() { @Override
public void run() {
Looper.prepare();
Toast.makeText(mContext, "很抱歉,程序出现异常,即将重启.", Toast.LENGTH_LONG).show();
Looper.loop();
     }
}.start();
// 收集设备参数信息
collectDeviceInfo(mContext);
// 保存日志文件
saveCrashInfoFile(ex);
// 重启应用(按需要添加是否重启应用)
Intent intent =
mContext.getPackageManager().getLaunchIntentForPackage(mContext.getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(intent);
// SystemClock.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
} 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 + "";
String versionCode = pi.versionCode + "";
infos.put("versionName", versionName);
infos.put("versionCode", versionCode);
}
} catch (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());
} catch (Exception e) {
Log.e(TAG, "an error occured when collect crash info", e);
}
}
} /**
* 保存错误信息到文件中
*
* @param ex
* @return 返回文件名称, 便于将文件传送到服务器
* @throws Exception
*/
private String saveCrashInfoFile(Throwable ex) throws Exception {
StringBuffer sb = new StringBuffer();
try {
SimpleDateFormat sDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String date = sDateFormat.format(new java.util.Date());
sb.append("\r\n" + date + "\n");
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.flush();
printWriter.close();
String result = writer.toString();
sb.append(result); String fileName = writeFile(sb.toString());
return fileName;
} catch (Exception e) {
Log.e(TAG, "an error occured while writing file...", e);
sb.append("an error occured while writing file...\r\n");
writeFile(sb.toString());
}
return null;
} private String writeFile(String sb) throws Exception {
String time = formatter.format(new Date());
// String fileName = "partylive-" + time + ".log";
String fileName = "partylive-" + time + ".txt";
if (hasSdcard()) {
String path = getGlobalpath();
File dir = new File(path);
if (!dir.exists())
dir.mkdirs(); FileOutputStream fos = new FileOutputStream(path + fileName, true);
fos.write(sb.getBytes());
fos.flush();
fos.close();
}
return fileName;
} public static String getGlobalpath() {
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "partylive" + File.separator;
} public static void setTag(String tag) {
TAG = tag;
} /**
* 判断SD卡是否可用
*
* @return SD卡可用返回true
*/
public static boolean hasSdcard() {
String status = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(status);
}
}
												

错误Log日志的收集的更多相关文章

  1. Appium python自动化测试系列之日志的收集(十二)

    ​13.1 日志的定义 13.1.1 日志的定义 听到日志这个东西可能有的人莫名其妙,第一次接触就会觉得我们为什么要收集日志,即使要收集日志那么我们需要收集哪些日志,日志的作用是什么等等. 其实日志无 ...

  2. Linux操作系统log日志日志分别指什么

    Linux操作系统log日志日志分别指什么 2019-04-20    20:41:05 一.一般的日志 /var/log/messages —包括整体系统信息,其中也包含系统启动期间的日志.此外,m ...

  3. 数据库 alert.log 日志中出现 "[Oracle][ODBC SQL Server Wire Protocol driver][SQL Server] 'RECOVER'"报错信息

    现象描述: (1).数据库通过调用透明网络实现分布式事务,但透明网关停用后,失败的分布式事务并未清理. (2).数据库 alert 日志 Thu Sep 06 06:53:00 2018 Errors ...

  4. 全栈必备Log日志

    Log日志,不论对开发者自身,还是对软件系统乃至产品服务都是非常重要的事情.每个开发者都接触过日志,以至于每个人对日志的了解都会有所不同. 什么是日志 日志是什么呢?老码农看来,日志是带有明确时间标记 ...

  5. 使用Elasticsearch、Logstash、Kibana与Redis(作为缓冲区)对Nginx日志进行收集(转)

    摘要 使用Elasticsearch.Logstash.Kibana与Redis(作为缓冲区)对Nginx日志进行收集 版本 elasticsearch版本: elasticsearch-2.2.0 ...

  6. java中关于log日志

    博:http://zhw2527.iteye.com/blog/1006302 http://zhw2527.iteye.com/blog/1099658 在项目开发中,记录错误日志是一个很有必要功能 ...

  7. AOP 切面编程------JoinPoint ---- log日志

    AOP 在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.AOP是OOP的延续,是软件 ...

  8. Android的log日志知识点剖析

    log类的继承结构 Log public final class Log extends Object java.lang.Object ↳ android.util.Log log日志的常用方法 分 ...

  9. 转 -Filebeat + Redis 管理 LOG日志实践

    Filebeat + Redis 管理 LOG日志实践 小赵营 关注 2019.01.06 17:52* 字数 1648 阅读 24评论 0喜欢 2 引用 转载 请注明出处 某早上,领导怒吼声远远传来 ...

随机推荐

  1. poj 2100(尺取法)

    Graveyard Design Time Limit: 10000MS   Memory Limit: 64000K Total Submissions: 6107   Accepted: 1444 ...

  2. LeetCode OJ-- Maximum Subarray @

    https://oj.leetcode.com/problems/maximum-subarray/ 给了一个数组一列数,求其中的连续子数组的最大和. O(n)复杂度 class Solution { ...

  3. python对象的复制问题

    list 的拷贝问题: 1, >>> a [1, 2] >>> b=a[:] >>> b [1, 2] >>> b[0]=20 ...

  4. 洛谷——P1996 约瑟夫问题

    P1996 约瑟夫问题 (什么?!要给学弟学妹讲约瑟夫问题?!难道就不怕我给他们讲错了吗?! 啊啊啊,为了不给学弟学妹们讲错,蒟蒻表示要临阵磨一下刀...) 题目背景 约瑟夫是一个无聊的人!!! 题目 ...

  5. codevs——1220 数字三角形(棋盘DP)

     时间限制: 1 s  空间限制: 128000 KB  题目等级 : 黄金 Gold 题解       题目描述 Description 如图所示的数字三角形,从顶部出发,在每一结点可以选择向左走或 ...

  6. IIS 7 Access to the path ‘c:\windows\system32\inetsrv\’ is denied

    https://randypaulo.wordpress.com/2011/09/13/iis-7-access-to-the-path-cwindowssystem32inetsrv-isdenie ...

  7. IOS7开发~API变化

    1.弃用 MKOverlayView 及其子类,使用类 MKOverlayRenderer: 2.弃用 Audio Toolbox framework 中的 AudioSession API,使用AV ...

  8. navicat链接lunix平台上的数据库

    xsell 4.navicat软件 想在链接数据库的得常规设置里设置: 链接名称.主机名(链接lunix平台后才干ping 通的ip地址) port.username.password 然后选择ssh ...

  9. (转)ubuntu/var/log/下各个日志文件

    本文简单介绍ubuntu/var/log/下各个日志文件,方便出现错误的时候查询相应的log   /var/log/alternatives.log-更新替代信息都记录在这个文件中 /var/log/ ...

  10. struts2设置默认首页

    在默认情况下,我们一般希望.当我们在浏览器中输入127.0.0.1:8080/project_name时候跳到项目的首页,那么在struts中我们这么设置呢?光加上<default-action ...