Java 将 Logcat 保存到 Android 设备中的文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19565685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:22:56  来源:igfitidea点击:

Saving Logcat to a text file in Android Device

javaandroideclipselogcatandroid-sdcard

提问by Nithin Michael

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?

我在 android 设备中运行应用程序时发现了一些崩溃,这在模拟器中没有显示。所以我需要将 Logcat 保存在设备内存或 SD 卡中的文本文件中。你能建议我这样做的好方法吗?

采纳答案by Sarath Nagesh

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.

在应用程序的开头使用 Application 类。这允许正确的文件和日志处理。这是一个例子。这段代码将一个名为“MyPersonalAppFolder”的新文件夹和另一个名为“log”的文件夹添加到公共外部存储中。之后清除logcat输出并将新的logcat输出写入一个名为logcatXXX.txt的新文件,其中XXX是此时的毫秒时间。

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:

您需要在 .manifest 文件中获得正确的权限和应用程序类的名称:

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

现在运行您的应用程序并转到“/您的外部存储/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");

回答by smophos

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.

转到您的终端/命令提示符并导航到其中包含 adb 的文件夹,如果它尚未添加到您的环境变量中并粘贴此命令。

t is the number lines you need to view

t 是您需要查看的数字线

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

D:\logcat_output.txt 是您的 logcat 将被存储的地方。

回答by d3n13d1

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

回答by Tapa Save

If you only need to save the logcat (without your coding) you can use aLogrecor aLogcatapplications from Google Play.

如果您只需要保存 logcat(无需编码),您可以使用Google Play 中的aLogrecaLogcat应用程序。

Google Play Store: aLogcat & aLogrec

Google Play 商店:aLogcat 和 aLogrec

回答by Green goblin

Use -f option with logcat in your class:

在您的班级中将 -f 选项与 logcat 一起使用:

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.

请注意,路径“/sdcard/”可能并非在所有设备中都可用。您应该使用标准 API 来访问外部存储

回答by Carlos Eduardo Millani

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 permissionat Run Time, I had to add the following:

我按照@HeisenBerg 说的做了,对我来说效果很好,但是由于从 android 6.0 开始,我们必须在运行时请求许可,因此我必须添加以下内容:

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

只在回调 onRequestPermissionsResult

回答by Pablo Valdes

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

显然android.permission.READ_LOGS仅授予最新版本的 Android 中的系统应用程序。