Collect all Log.d from class and save it into SDCa

2019-02-25 03:41发布

Hey is it possible in Android to collect all Log.d from one class and keep on appending it and save it into SDCard ?

For example :

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*/

}

3条回答
Lonely孤独者°
2楼-- · 2019-02-25 03:54

You can override the Log class and do that yourself. But is it really required for your purposes?

查看更多
forever°为你锁心
3楼-- · 2019-02-25 03:56

You can get all logs with the logcat command. You can try something like:

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();
    }
}

You can get more information about logcat here: http://developer.android.com/tools/help/logcat.html

查看更多
男人必须洒脱
4楼-- · 2019-02-25 03:58

no, Log.* methods write to the console, however you can use Logger http://developer.android.com/reference/java/util/logging/Logger.html and a FileHandler

查看更多
登录 后发表回答