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. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值