3

嘿,在 Android 中是否可以从一个类中收集所有 Log.d 并继续附加它并将其保存到 SDCard 中?

例如 :

Class Android {

    private final static String TAG = "hello";

    public void abcd(){
    Log.d(TAG, "it went into abcd method");
    }

    public void efgh(){
    Log.d(TAG, "it went into efgh method");
    }

       /*Here collect all above LOGS and write to file in SDCard*/

}
4

4 回答 4

3

logcat您可以使用该命令获取所有日志。您可以尝试以下方法:

public static void printLog(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();
    }
}

您可以在此处获取更多信息:http logcat: //developer.android.com/tools/help/logcat.html

于 2013-07-12T07:26:06.590 回答
0

不,Log.* 方法写入控制台,但是您可以使用 Logger http://developer.android.com/reference/java/util/logging/Logger.html和 FileHandler

于 2013-07-12T07:34:01.250 回答
0

您可以覆盖 Log 类并自己执行此操作。但它真的为您的目的所必需吗?

于 2013-07-12T07:27:30.770 回答
0

如果要添加带有标签名称的日志和

logcat -s <Tagname>

不适合你,那么你可以做这个把戏

//... Brtle 's code..(accepted one )
    file.createNewFile();
       FileWriter writer = new FileWriter(file);
         while((line = in.readLine()) != null){
             if(line.contains("TAG_NAME")){ // Trick :-)
                writer.write(line + "\n");
               }
             }
于 2020-03-10T20:55:27.883 回答