一、自定义抓取错误日志的工具类

1、获取app奔溃日志的工具类

com.happyparking.utilsandroid.content.Contextandroid.content.pm.PackageInfoandroid.content.pm.PackageManagerandroid.os.Buildandroid.os.Looperandroid.util.Logjava.io.Filejava.io.FileOutputStreamjava.io.PrintWriterjava.io.StringWriterjava.io.Writerjava.lang.Thread.UncaughtExceptionHandlerjava.lang.reflect.FieldCrashHandler UncaughtExceptionHandler {

    String = = Thread.UncaughtExceptionHandler CrashHandler Context CrashHandler() {
    }

    CrashHandler () {
        (CrashHandler.) {
            (== ) {
                = CrashHandler()}
        }

        }

    (Context ctx) {
        = ctx= Thread.()Thread.()}

    (Thread threadThrowable ex) {
        (!handleException(ex) && != ) {
            .uncaughtException(threadex)} { {
                Thread.()} (InterruptedException e) {
            }
            android.os.Process.(android.os.Process.())System.()}

    }

    (Throwable ex) {
        (ex == ) {
            }
        String errorInfo = getErrorInfo(ex)String versioninfo = getVersionInfo()String mobileInfo = getMobileInfo()Thread() {
            () {
                Looper.(){
                    Log.()= + getVersionInfo() + File file = File(SDCardUtil.)FileOutputStream fos = FileOutputStream(file)fos.write(.getBytes())fos.write(.getBytes())fos.write(.getBytes())fos.flush()fos.close()} (Exception e) {
                    Log.(+ e.toString())}
                Looper.()}

        }.start()}

    String (Throwable arg1) {
        Writer writer = StringWriter()PrintWriter pw = PrintWriter(writer)arg1.printStackTrace(pw)pw.close()String error = writer.toString()error}

    String () {
        StringBuffer sb = StringBuffer(){

            Field[] fields = Build..getDeclaredFields()(Field field : fields) {
                field.setAccessible()String name = field.getName()String value = field.get().toString()sb.append(name + + value)sb.append()}
        } (Exception e) {
            e.printStackTrace()}
        sb.toString()}

    String () {
        {
            PackageManager pm = .getPackageManager()PackageInfo info = pm.getPackageInfo(.getPackageName())info.} (Exception e) {
            e.printStackTrace()}
    }
}

2、第二步在app程序入口对应的Application的oncreat()方法中调用init方法即可。

CrashHandler cashHandler = CrashHandler.getInstance();//抓取错误日志
cashHandler.init(instance);



二、使用第三方库AndroidLogCollector,使用方法如下:

AndroidLogCollector

android app崩溃日志收集sdk 1.0


作者:贾博士

崩溃日志收集方法:

1.LogCollector是lib包,在需要添加崩溃日志sdk的工程中导入此包。

2.导入lib后,在自己的工程的AndroidManifest.xml文件中加入权限:

        <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

3.在自己的工程中重写自己的application,在oncreate中加入

    LogCollector.init(getApplicationContext(), UPLOAD_URL, params);

PS:重写自己的application记得在Manifest注册

参数:

1.Context

2.String UPLOAD_URL ,上传地址url,支持http和https方式,post方法。

3.HttpParameters params ,自定义的类,用于post上传其他参数。

说明:

发生崩溃后,日志会保存在 /data/data/{your package name}/files/ 目录下

日志只有一个文件,多条数据日志保存

日志文件上传成功后会自动删除,上传不成功则不删除

日志格式可以根据自己的需求在源码中改动

http的post传的数据也可自行修改

参考代码:

    public class MyApplication extends Application {
        //post method , upload logfile url,replace your site . support http or https
        private static final String UPLOAD_URL = "http://xxxxxxxx";

        @Override
        public void onCreate() {
        super.onCreate();

        //upload logfile , post params.
        HttpParameters params = new HttpParameters();
        params.add("key1", "value1");
        params.add("key2", "value2");
        params.add("key3", "value3");
        //.......
        //replace your key and value;

        boolean isDebug = true;
        //set debug mode , you can see debug log , and also you can get logfile in sdcard;
        LogCollector.setDebugMode(isDebug);
        LogCollector.init(getApplicationContext(), UPLOAD_URL, params);//params can be null
        }
    }

上传日志方法:

需要先在application中执行init,

然后在任何位置添加如下代码:

    LogCollector.upload(boolean isWifiOnly);

参数:

1.boolean isWifiOnly; true代表只在wifi情况下发送,false代表有网的情况下就发送(包括流量和wifi)

您可以在service,activity等位置的合适时机触发,不会卡界面也不会影响性能。

参考代码:

    private void uploadLogFile(){
    boolean isWifiOnly = true;//only wifi mode can upload
    LogCollector.upload(isWifiOnly);//upload at the right time
    }

调试:

在init之前调用

    LogCollector.setDebugMode(boolean isDebug);

说明:

1.开启调试后可以看到堆栈的log信息

2.同时可以在sd卡下的Android/data/{your package name}/Log/ 目录下可以查看保存的崩溃log日志

该目录下的日志不会自动删除,请及时清空,避免占用空间



三、收集系统日志:

读取日志需要的权限

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

主要代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package  mt.fzgh;
 
import  java.io.BufferedReader;
import  java.io.InputStreamReader;
import  java.util.ArrayList;
 
public  class  MyLog
{
     public  static  class  MLog     //静态类
     {
         public  static  void  getLog()
         {
             System.out.println( "--------func start--------" );  // 方法启动
             try
             {
                 ArrayList<String> cmdLine= new  ArrayList<String>();    //设置命令   logcat -d 读取日志
                 cmdLine.add( "logcat" );
                 cmdLine.add( "-d" );
                 
                 ArrayList<String> clearLog= new  ArrayList<String>();   //设置命令  logcat -c 清除日志
                 clearLog.add( "logcat" );
                 clearLog.add( "-c" );
                 
                 Process process=Runtime.getRuntime().exec(cmdLine.toArray( new  String[cmdLine.size()]));    //捕获日志
                 BufferedReader bufferedReader= new  BufferedReader( new  InputStreamReader(process.getInputStream()));     //将捕获内容转换为BufferedReader
                 
 
//                Runtime.runFinalizersOnExit(true);
                 String str= null ;
                 while ((str=bufferedReader.readLine())!= null )     //开始读取日志,每次读取一行
                 {
                     Runtime.getRuntime().exec(clearLog.toArray( new  String[clearLog.size()]));   //清理日志....这里至关重要,不清理的话,任何操作都将产生新的日志,代码进入死循环,直到bufferreader满
                     System.out.println(str);     //输出,在logcat中查看效果,也可以是其他操作,比如发送给服务器..
                 }
                 if (str== null )
                 {
                     System.out.println( "--   is null   --" );
                 }
             }
             catch (Exception e)
             {
                 e.printStackTrace();
             }
             System.out.println( "--------func end--------" );
         }
     }
}

这里比较令人纠结的一点就是日志的清理  logcat -c  如果不加入 清理 在buffer满为止,代码自身能够迭代6~7次....


附带一份logcat的 命令...不过好像 过滤器 指令有问题....慎用

选项           说明    

-s               默认设置过滤器    

- f 文件       输出到日志文件    

-c               清除日志    

-d               获取日志    

-g               获取日志的大小    

- v 格式      设置日志(见下面的格式打印格式)

   


- v 格式                       例

brief                            W/tag ( 876): message

process                      W( 876) message (tag)

tag                             W/tag : message

thread                        W( 876:0x37c) message

raw                            message

time                           09-08 05:40:26.729 W/tag ( 876): message

threadtime                 09-08 05:40:26.729 876 892 W tag : message

long                           [09-08 05:40:26.729 876:0x37c W/tag ] message


如若满意,请点击右侧【采纳答案】,如若还有问题,请点击【追问】

希望我的回答对您有所帮助,望采纳!