Saving Logcat to a text file in Android Device

梦想与她 提交于 2019-11-27 05:07:36

问题


I had found some crashes while running the application in android device, which is not showing in emulator. So i need to save the Logcat in a text file in my device's memory or SD card. Could you please suggest me good method to do this?


回答1:


use a Application class at the beginning of your app. That allows a proper file and log handling. Here is an example. That piece of code adds a new folder named “MyPersonalAppFolder” with another folder called “log” in it to the public external storage. after that the logcat output is cleared and the new logcat output is written into a new file called logcatXXX.txt, where XXX is the are the milliseconds time at this moment.

public class MyPersonalApp extends Application {

    /**
     * Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created.
     */
    public void onCreate() {
        super.onCreate();

        if ( isExternalStorageWritable() ) {

            File appDirectory = new File( Environment.getExternalStorageDirectory() + "/MyPersonalAppFolder" );
            File logDirectory = new File( appDirectory + "/log" );
            File logFile = new File( logDirectory, "logcat" + System.currentTimeMillis() + ".txt" );

            // create app folder
            if ( !appDirectory.exists() ) {
                appDirectory.mkdir();
            }

            // create log folder
            if ( !logDirectory.exists() ) {
                logDirectory.mkdir();
            }

            // clear the previous logcat and then write the new one to the file
            try {
                Process process = Runtime.getRuntime().exec("logcat -c");
                process = Runtime.getRuntime().exec("logcat -f " + logFile);
            } catch ( IOException e ) {
                e.printStackTrace();
            }

        } else if ( isExternalStorageReadable() ) {
            // only readable
        } else {
            // not accessible
        }
    }

    /* Checks if external storage is available for read and write */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if ( Environment.MEDIA_MOUNTED.equals( state ) ) {
            return true;
        }
        return false;
    }

    /* Checks if external storage is available to at least read */
    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        if ( Environment.MEDIA_MOUNTED.equals( state ) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals( state ) ) {
            return true;
        }
        return false;
    }
}

you need the correct permissions and name of your application class in your .manifest file:

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

<application
    android:name=".MyPersonalApp"
    ... >

Now run your application and goto "/your external storage/MyPersonalAppFolder/logs/"

You'll find log file there.

Edit:

if you want to save log of only some particular activities..

replace:

process = Runtime.getRuntime().exec("logcat -f " + logFile);

with:

process = Runtime.getRuntime().exec( "logcat -f " + logFile + " *:S MyActivity:D MyActivity2:D");



回答2:


adb shell logcat -t 500 > D:\logcat_output.txt

Go onto your terminal/command prompt and navigate to the folder with adb in it, if its not already added to your environmental variables and paste this command.

t is the number lines you need to view

D:\logcat_output.txt is where your logcat will get stored.




回答3:


Use -f option with logcat in your class:

Runtime.getRuntime().exec("logcat -f" + " /sdcard/Logcat.txt");

This will dump the logs to the file stored device.

Note that the path "/sdcard/" may not be available in all devices. You should use the standard APIs to access the external storage.




回答4:


As I cannot comment yet, I`ll post this as an answer

I did as @HeisenBerg said, worked fine for me, but since from android 6.0 on we have to ask for permission at Run Time, I had to add the following:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if(checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    }
}

And call

process = Runtime.getRuntime().exec("logcat -f " + logFile);

Only on the callback onRequestPermissionsResult




回答5:


Add the manifest permission:

uses-permission android:name="android.permission.READ_LOGS" 


private static final String COMMAND = "logcat -d -v time";


public static void fetch(OutputStream out, boolean close) throws IOException {
    byte[] log = new byte[1024 * 2];
    InputStream in = null;
    try {
        Process proc = Runtime.getRuntime().exec(COMMAND);
        in = proc.getInputStream();
        int read = in.read(log);
        while (-1 != read) {
            out.write(log, 0, read);
            read = in.read(log);
        }
    }
    finally {
        if (null != in) {
            try {
                in.close();
            }
            catch (IOException e) {
                // ignore
            }
        }

        if (null != out) {
            try {
                out.flush();
                if (close)
                    out.close();
            }
            catch (IOException e) {
                // ignore
            }
        }
    }
}

public static void fetch(File file) throws IOException {
    FileOutputStream fos = new FileOutputStream(file);
    fetch(fos, true);
}



回答6:


If you only need to save the logcat (without your coding) you can use aLogrec or aLogcat applications from Google Play.

Google Play Store: aLogcat & aLogrec




回答7:


Apparently android.permission.READ_LOGS is only granted to system apps in latest versions of Android.



来源:https://stackoverflow.com/questions/19565685/saving-logcat-to-a-text-file-in-android-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!