android開發之應用Crash自動抓取Log_自動保存崩潰日志到本地


http://blog.csdn.net/jason0539/article/details/45602655

應用發生crash之后要查看log,判斷問題出在什么地方,可是一旦應用發布出去,就要想辦法把用戶的崩潰日志拿到分析。

所以要在發生crash之后抓取log,然后上傳到服務器,方便開發者查看,現在都有很多第三方做這方面的服務,這里說下如何自己來實現。

其實原理很簡單,應用出現異常后,會由默認的異常處理器來處理異常,

我們要做的就是把這個任務接管過來,自己處理異常,包括收集日志,保存到本地,然后上傳到服務器。

下面是自己實現的異常處理類。

 

[java]  view plain  copy
 
 print?
  1. public class CrashHandler implements UncaughtExceptionHandler {  
  2.     public static final String TAG = "CrashHandler";  
  3.   
  4.     // 系統默認的UncaughtException處理類  
  5.     private Thread.UncaughtExceptionHandler mDefaultHandler;  
  6.     // CrashHandler實例  
  7.     private static CrashHandler INSTANCE = new CrashHandler();  
  8.     // 程序的Context對象  
  9.     private Context mContext;  
  10.     // 用來存儲設備信息和異常信息  
  11.     private Map<String, String> infos = new HashMap<String, String>();  
  12.   
  13.     // 用於格式化日期,作為日志文件名的一部分  
  14.     private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");  
  15.     private String nameString;  
  16.   
  17.     /** 保證只有一個CrashHandler實例 */  
  18.     private CrashHandler() {  
  19.     }  
  20.   
  21.     /** 獲取CrashHandler實例 ,單例模式 */  
  22.     public static CrashHandler getInstance() {  
  23.         return INSTANCE;  
  24.     }  
  25.   
  26.     /** 
  27.      * 初始化 
  28.      *  
  29.      * @param context 
  30.      */  
  31.     public void init(Context context) {  
  32.         mContext = context;  
  33.         // 獲取系統默認的UncaughtException處理器  
  34.         mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();  
  35.         // 設置該CrashHandler為程序的默認處理器  
  36.         Thread.setDefaultUncaughtExceptionHandler(this);  
  37.         nameString = BmobUserManager.getInstance(mContext).getCurrentUserName();  
  38.     }  
  39.   
  40.     /** 
  41.      * 當UncaughtException發生時會轉入該函數來處理 
  42.      */  
  43.     @Override  
  44.     public void uncaughtException(Thread thread, Throwable ex) {  
  45.         if (!handleException(ex) && mDefaultHandler != null) {  
  46.             // 如果用戶沒有處理則讓系統默認的異常處理器來處理  
  47.             mDefaultHandler.uncaughtException(thread, ex);  
  48.         } else {  
  49.             try {  
  50.                 Thread.sleep(3000);  
  51.             } catch (InterruptedException e) {  
  52.                 Log.e(TAG, "error : ", e);  
  53.             }  
  54.             // 退出程序  
  55.             android.os.Process.killProcess(android.os.Process.myPid());  
  56.             System.exit(1);  
  57.         }  
  58.     }  
  59.   
  60.     /** 
  61.      * 自定義錯誤處理,收集錯誤信息 發送錯誤報告等操作均在此完成. 
  62.      *  
  63.      * @param ex 
  64.      * @return true:如果處理了該異常信息;否則返回false. 
  65.      */  
  66.     private boolean handleException(Throwable ex) {  
  67.         if (ex == null) {  
  68.             return false;  
  69.         }  
  70.         WonderMapApplication.getInstance().getSpUtil().setCrashLog(true);// 每次進入應用檢查,是否有log,有則上傳  
  71.         // 使用Toast來顯示異常信息  
  72.         new Thread() {  
  73.             @Override  
  74.             public void run() {  
  75.                 Looper.prepare();  
  76.                 Toast.makeText(mContext, "很抱歉,程序出現異常,正在收集日志,即將退出", Toast.LENGTH_LONG)  
  77.                         .show();  
  78.                 Looper.loop();  
  79.             }  
  80.         }.start();  
  81.         // 收集設備參數信息  
  82.         collectDeviceInfo(mContext);  
  83.         // 保存日志文件  
  84.         String fileName = saveCrashInfo2File(ex);  
  85.         return true;  
  86.     }  
  87.   
  88.     /** 
  89.      * 收集設備參數信息 
  90.      *  
  91.      * @param ctx 
  92.      */  
  93.     public void collectDeviceInfo(Context ctx) {  
  94.         try {  
  95.             PackageManager pm = ctx.getPackageManager();  
  96.             PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),  
  97.                     PackageManager.GET_ACTIVITIES);  
  98.             if (pi != null) {  
  99.                 String versionName = pi.versionName == null ? "null"  
  100.                         : pi.versionName;  
  101.                 String versionCode = pi.versionCode + "";  
  102.                 infos.put("versionName", versionName);  
  103.                 infos.put("versionCode", versionCode);  
  104.             }  
  105.         } catch (NameNotFoundException e) {  
  106.             Log.e(TAG, "an error occured when collect package info", e);  
  107.         }  
  108.         Field[] fields = Build.class.getDeclaredFields();  
  109.         for (Field field : fields) {  
  110.             try {  
  111.                 field.setAccessible(true);  
  112.                 infos.put(field.getName(), field.get(null).toString());  
  113.                 Log.d(TAG, field.getName() + " : " + field.get(null));  
  114.             } catch (Exception e) {  
  115.                 Log.e(TAG, "an error occured when collect crash info", e);  
  116.             }  
  117.         }  
  118.     }  
  119.   
  120.     /** 
  121.      * 保存錯誤信息到文件中 
  122.      *  
  123.      * @param ex 
  124.      * @return 返回文件名稱,便於將文件傳送到服務器 
  125.      */  
  126.     private String saveCrashInfo2File(Throwable ex) {  
  127.   
  128.         StringBuffer sb = new StringBuffer();  
  129.         for (Map.Entry<String, String> entry : infos.entrySet()) {  
  130.             String key = entry.getKey();  
  131.             String value = entry.getValue();  
  132.             sb.append(key + "=" + value + "\n");  
  133.         }  
  134.   
  135.         Writer writer = new StringWriter();  
  136.         PrintWriter printWriter = new PrintWriter(writer);  
  137.         ex.printStackTrace(printWriter);  
  138.         Throwable cause = ex.getCause();  
  139.         while (cause != null) {  
  140.             cause.printStackTrace(printWriter);  
  141.             cause = cause.getCause();  
  142.         }  
  143.         printWriter.close();  
  144.         String result = writer.toString();  
  145.         L.d(WModel.CrashUpload, result);  
  146.         sb.append(result);  
  147.         try {  
  148.             long timestamp = System.currentTimeMillis();  
  149.             String time = formatter.format(new Date());  
  150.             String fileName = nameString + "-" + time + "-" + timestamp  
  151.                     + ".log";  
  152.             if (Environment.getExternalStorageState().equals(  
  153.                     Environment.MEDIA_MOUNTED)) {  
  154.                 String path = WMapConstants.CrashLogDir;  
  155.                 File dir = new File(path);  
  156.                 if (!dir.exists()) {  
  157.                     dir.mkdirs();  
  158.                 }  
  159.                 FileOutputStream fos = new FileOutputStream(path + fileName);  
  160.                 fos.write(sb.toString().getBytes());  
  161.                 fos.close();  
  162.             }  
  163.             return fileName;  
  164.         } catch (Exception e) {  
  165.             Log.e(TAG, "an error occured while writing file...", e);  
  166.         }  
  167.         return null;  
  168.     }  
  169.   
  170. }  


使用方式如下:

 

在Application的onCreate中加上下面

 

[java]  view plain  copy
 
 print?
  1. CrashHandler crashHandler = CrashHandler.getInstance();  
  2. crashHandler.init(this);  


這樣一來,應用發生crash,自動保存log到本地了。

 

其實這樣還有一個好處,就是不用在logcat里面翻來翻去找日志,直接到本地文件夾打開看就是了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM