以编程方式在Android中过滤日志

时间:2013-07-15 06:03:50

标签: android logging

这是在SDCard for Android中获取和转储日志的方法。这工作正常,但我想知道我们是否可以使用过滤器跟踪与特定标签相关的日志。

我试过了logcat -s *TagIWant;,但它没有用。还有其他建议吗?

public static void Log(Context context){
    String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
    String command = "logcat -d *:V";

    Log.d(TAG, "command: " + command);

    try{
        Process process = Runtime.getRuntime().exec(command);

        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        try{
            File file = new File(filename);
            file.createNewFile();
            FileWriter writer = new FileWriter(file);
            while((line = in.readLine()) != null){
                writer.write(line + "\n");
            }
            writer.flush();
            writer.close();
        }
        catch(IOException e){
            e.printStackTrace();
        }
    }
    catch(IOException e){
        e.printStackTrace();
    }
}

3 个答案:

答案 0 :(得分:0)

try {               
        Process process = Runtime.getRuntime().exec("logcat -d");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line;

        Pattern pattern = Pattern.compile("XXX", 0);

        while ((line = bufferedReader.readLine()) != null) {
            if (patternu != null
                    && !pattern.matcher(line).find()) {
                continue;
            }
            log.append(line);
            log.append('\n');
        }

    } catch (IOException e) {

    }

答案 1 :(得分:0)

将“Your_Tag”替换为您的标记,它将为您提供带有标记的日志,其中包含优先级为“Debug”及以上的标记。

String command = "logcat Your_Tag:D *:S";
Process process = Runtime.getRuntime().exec(command);

http://developer.android.com/tools/debugging/debugging-log.html

上查看更多内容

答案 2 :(得分:0)

您可以像下面的代码一样轻松过滤要编写的行:

  while ((line = bufferedReader.readLine()) != null) {
            if(line.contains("The String you want to exist in your log")){
                writer.write(line + "\n");
            }
            else{continue;}
        }