【问题标题】:Save android logcat in a file on Android device将 android logcat 保存在 Android 设备上的文件中
【发布时间】:2017-07-19 08:57:26
【问题描述】:

我想将 Android logcat 写入我设备上的文件中。 为此,我使用了以下代码

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

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

        if(!appDirectory.exists()){
            appDirectory.mkdir();
        }

        if(!logDirectory.exists()){
            logDirectory.mkdir();
        }

        if(!logFile.exists()){
            try {
                logFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try{
            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);
                    Process process = Runtime.getRuntime().exec("logcat -f "+logFile);
                }
            }
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
    else if (isExternalStorageReadable()){
        Log.i(TAG, "ONLY READABLE");
    }
    else{
        Log.i(TAG, "NOT ACCESSIBLE");
    }}

    public boolean isExternalStorageReadable(){

    String state = Environment.getExternalStorageState();
    if(Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
        return true;
    }
    return false;
}
   public boolean isExternalStorageWritable(){

    String state = Environment.getExternalStorageState();
    if(Environment.MEDIA_MOUNTED.equals(state)){
        return true;
    }
    return false;
}

我在 AndroidManifest.xml 中添加了权限

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

文件夹和文件已创建,但文件始终为空。 如何改进代码以便将 logcat 写入文件中。

【问题讨论】:

  • 你在哪里写内容到文件?
  • 如果您将在比 marshmallow 旧的设备上运行您的应用程序,Logcat 将不会存储在文件中
  • 安卓版本为6.0.1。

标签: android android-logcat


【解决方案1】:
if(checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

}
else{
Process process = Runtime.getRuntime().exec("logcat -f "+logFile);
}

您的代码运行良好可能是您错误地写了请求许可并一起制作日志文件

【讨论】:

    【解决方案2】:

    也许您没有将日志写入文件。您缺少此方法。

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

    您从这个问题Stack overflow question 的解决方案中获取了代码。看看吧。

    【讨论】:

    • 是的,我从你提到的问题中得到了解决方案。我的代码中有这个功能
    • 尝试在设备setting&gt;select your app&gt;permissions&gt;switch all the permission 中为您的应用授予权限。不确定,但请尝试一下。
    【解决方案3】:

    很高兴回答你的问题。

    在我的项目中,我用这个来解决问题。

    1.添加这个类

    public class LogcatHelper {
    
    private static LogcatHelper INSTANCE = null;
    private static String PATH_LOGCAT;
    private LogDumper mLogDumper = null;
    private int mPId;
    
    /**
     * init data
     */
    public void init(Context context) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {// sd first
            PATH_LOGCAT = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + File.separator + "logcat";
        } else {
            PATH_LOGCAT = context.getFilesDir().getAbsolutePath()
                    + File.separator + "logcat";
        }
        File file = new File(PATH_LOGCAT);
        if (!file.exists()) {
            file.mkdirs();
        }
    }
    
    public static LogcatHelper getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new LogcatHelper(context);
        }
        return INSTANCE;
    }
    
    private LogcatHelper(Context context) {
        init(context);
        mPId = android.os.Process.myPid();
    }
    
    public void start() {
        if (mLogDumper == null)
            mLogDumper = new LogDumper(String.valueOf(mPId), PATH_LOGCAT);
        mLogDumper.start();
    }
    
    public void stop() {
        if (mLogDumper != null) {
            mLogDumper.stopLogs();
            mLogDumper = null;
        }
    }
    
    private class LogDumper extends Thread {
    
        private Process logcatProc;
        private BufferedReader mReader = null;
        private boolean mRunning = true;
        String cmds = null;
        private String mPID;
        private FileOutputStream out = null;
    
        public LogDumper(String pid, String dir) {
            mPID = pid;
            try {
                out = new FileOutputStream(new File(dir, "logcat"
                        + getFileName() + ".log"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
    
            /**
             *
             * Level:*:v , *:d , *:w , *:e , *:f , *:s
             *
             *
             * */
    
            // cmds = "logcat *:e *:w | grep \"(" + mPID + ")\""; // print e level and ilevel info
            // cmds = "logcat  | grep \"(" + mPID + ")\"";// print all
            // cmds = "logcat -s way";// print filter info
            cmds = "logcat *:e *:i | grep \"(" + mPID + ")\"";
    
        }
    
        public void stopLogs() {
            mRunning = false;
        }
    
        @Override
        public void run() {
            try {
                logcatProc = Runtime.getRuntime().exec(cmds);
                mReader = new BufferedReader(new InputStreamReader(
                        logcatProc.getInputStream()), 1024);
                String line = null;
                while (mRunning && (line = mReader.readLine()) != null) {
                    if (!mRunning) {
                        break;
                    }
                    if (line.length() == 0) {
                        continue;
                    }
                    if (out != null && line.contains(mPID)) {
                        out.write((getDateEN() + "  " + line + "\n")
                                .getBytes());
                    }
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (logcatProc != null) {
                    logcatProc.destroy();
                    logcatProc = null;
                }
                if (mReader != null) {
                    try {
                        mReader.close();
                        mReader = null;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    out = null;
                }
    
            }
    
        }
    
    }
    
    public static String getFileName() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String date = format.format(new Date(System.currentTimeMillis()));
        return date;
    }
    
    public static String getDateEN() {
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date1 = format1.format(new Date(System.currentTimeMillis()));
        return date1;
    }
    

    }

    1. 在应用程序类中添加代码

      LogcatHelper.getInstance((getApplicationContext())).start();

    3.在Application类中添加权限

    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);
                    Process process = Runtime.getRuntime().exec("logcat -f "+logFile);
                }
            }
    

    希望能帮到你。

    【讨论】:

    • 感谢您的帮助。你的回答解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 2020-09-28
    • 1970-01-01
    相关资源
    最近更新 更多