Android 打印日誌

app在運行過程中,爲了後期的維護升級,記錄日誌是一個非常好的方法。

爲了讀取到app運行時的日誌,一般的作法是單獨開一個線程,在app運行的啓動線程,然後app退出時停掉線程。

然而我們更好的方法是開啓一個service,然後在裏面做日誌記錄,代碼如下:

[java] view plain copy
  1. package com.hai.logcat;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.DataInputStream;  
  5. import java.io.File;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10. import java.io.InputStreamReader;  
  11. import java.util.List;  
  12.   
  13. import android.app.ActivityManager;  
  14. import android.app.ActivityManager.RunningAppProcessInfo;  
  15. import android.app.Service;  
  16. import android.content.Intent;  
  17. import android.os.Environment;  
  18. import android.os.IBinder;  
  19. import android.os.Looper;  
  20. import android.util.Log;  
  21. import android.widget.Toast;  
  22.   
  23. public class MyLogcat extends Service {  
  24.     Thread thread;  
  25.     boolean readlog = true;  
  26.   
  27.     @Override  
  28.     public IBinder onBind(Intent intent) {  
  29.         return null;  
  30.     }  
  31.   
  32.     @Override  
  33.     public void onCreate() {  
  34.         super.onCreate();  
  35.         Log.d("hhp""onCreate");  
  36.         thread = new Thread(new Runnable() {  
  37.             @Override  
  38.             public void run() {  
  39.                 log2();//個人覺得這個方法更實用  
  40.             }  
  41.         });  
  42.     }  
  43.   
  44.     @Override  
  45.     public void onStart(Intent intent, int startId) {  
  46.         thread.start();  
  47.         Log.d("hhp""onStart");  
  48.         super.onStart(intent, startId);  
  49.     }  
  50.   
  51.     /** 
  52.      * 方法1 
  53.      */  
  54.     private void log2() {  
  55.         Log.d("hhp""log2 start");  
  56.         String[] cmds = { "logcat""-c" };  
  57.         String shellCmd = "logcat -v time -s *:W "// adb logcat -v time *:W  
  58.         Process process = null;  
  59.         Runtime runtime = Runtime.getRuntime();  
  60.         BufferedReader reader = null;  
  61.         try {  
  62.             runtime.exec(cmds).waitFor();  
  63.             process = runtime.exec(shellCmd);  
  64.             reader = new BufferedReader(new InputStreamReader(process.getInputStream()));  
  65.             String line = null;  
  66.             while ((line = reader.readLine()) != null) {  
  67.                 if (line.contains(String.valueOf(android.os.Process.myPid()))) {  
  68.                     // line = new String(line.getBytes("iso-8859-1"), "utf-8");  
  69.                     writeTofile(line);  
  70.                 }  
  71.             }  
  72.         } catch (Exception e) {  
  73.             e.printStackTrace();  
  74.         }  
  75.         Log.d("hhp""log2 finished");  
  76.     }  
  77.   
  78.     /** 
  79.      * 方法2 
  80.      */  
  81.     private void log() {  
  82.         Log.d("hhp""log start");  
  83.         String[] cmds = { "logcat""-c" };  
  84.         String shellCmd = "logcat -v time -s *:W ";// //adb logcat -v time *:W  
  85.         Process process = null;  
  86.         InputStream is = null;  
  87.         DataInputStream dis = null;  
  88.         String line = "";  
  89.         Runtime runtime = Runtime.getRuntime();  
  90.         try {  
  91.             runtime.exec(cmds);  
  92.             process = runtime.exec(shellCmd);  
  93.             is = process.getInputStream();  
  94.             dis = new DataInputStream(is);  
  95.             // String filter = GetPid();  
  96.             String filter = android.os.Process.myPid() + "";  
  97.             while ((line = dis.readLine()) != null) { //這裏如果輸入流沒斷,會一直循環下去。  
  98.                 line = new String(line.getBytes("iso-8859-1"), "utf-8");  
  99.                 if (line.contains(filter)) {  
  100.                     int pos = line.indexOf(":");  
  101.                     Log.d("hhp2", line + "");  
  102.                     writeTofile(line);  
  103.                 }  
  104.             }  
  105.         } catch (Exception e) {  
  106.         }  
  107.         Log.d("hhp""log finished");  
  108.     }  
  109.   
  110.     private void writeTofile(String line) {  
  111.         String content = line + "\r\n";  
  112.         File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()  
  113.                 + "/logcat/myLog.txt");  
  114.         if (!file.exists()) {  
  115.             try {  
  116.                 file.createNewFile();  
  117.             } catch (Exception e) {  
  118.                 e.printStackTrace();  
  119.             }  
  120.         }  
  121.         FileOutputStream fos;  
  122.         try {  
  123.             fos = new FileOutputStream(file, true);  
  124.             fos.write(content.getBytes());  
  125.             fos.flush();  
  126.             fos.close();  
  127.         } catch (Exception e) {  
  128.             e.printStackTrace();  
  129.         }  
  130.   
  131.     }  
  132.   
  133.     @Override  
  134.     public void onDestroy() {  
  135.         super.onDestroy();  
  136.         stopSelf();  
  137.     }  
  138. }  
代碼比較簡單,所以沒怎麼注視了。說下大概思路:在service開啓的時候,就開啓線程不停地從logcat中讀取輸入流,

把讀到的信息存入文件中,service停止的時候線程stop,就這麼簡單。

當然要讀入系統日誌還需要添加權限:

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

下面是我記錄的測試日誌,信息記錄的有點多,實際中可以運用正則過濾掉一些信息。


上面的代碼基本可以記錄本app運行中的日誌,但如果中途有未捕獲的異常導致app奔潰,那麼這個未捕獲的異常導致的奔潰上面代碼就記錄不到了。

因爲這個異常導致app奔潰,虛擬機掛掉,那當然記錄日誌的線程也停了。那怎麼捕獲這類我們未捕獲的異常(運行時異常)呢,幸好android這樣

一個接口UncaughtExceptionHandler,當app奔潰前,它會先通知這個接口,這樣我們就可以在app奔潰前做點自己想做的事了。

關於怎麼捕獲奔潰異常,我覺得這位哥們的一片博客寫的不錯http://blog.csdn.net/liuhe688/article/details/6584143#, 我借鑑着改了下:

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

上面我們實現了這個接口,然後在奔潰前做了一些友好處理,如存儲奔潰日誌,主動殺死進程,不讓彈出系統的強制關閉對話框。

然後我們在Application中這樣引用即可

[java] view plain copy
  1. package com.hai;  
  2.   
  3. import android.app.Application;  
  4.   
  5. import com.hai.logcat.CrashHandler;  
  6.   
  7. public class MyApplication extends Application {  
  8.     CrashHandler handler = null;  
  9.   
  10.     @Override  
  11.     public void onCreate() {  
  12.         super.onCreate();  
  13.         handler = CrashHandler.getInstance();  
  14.         handler.init(getApplicationContext());  
  15.     }  
  16. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章