如何在安卓系统中将日志写入SD卡?

4

我的程序在设备上崩溃了。我想在我的设备上运行程序并准确地捕获程序的日志,即将日志写入我的SD卡,直到崩溃发生为止。我该如何实现这一点?


你可以直接通过USB端口连接设备并运行应用程序,在DDMS中检查日志,为什么要将日志写入文件呢? - Lucifer
我不知道外部设备发生了什么事。我只是想知道如何将日志写入我的SD卡或其他位置。 - Strawberry
3
我不知道如何在设备中编写异常日志,但我已经使用ARCA来跟踪崩溃。 - maddy d
4个回答

8

试一下这个

Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this)); // add this to your activity page

public class ExceptionHandler implements
        java.lang.Thread.UncaughtExceptionHandler {
    private final Context myContext;
    private final String LINE_SEPARATOR = "\n";
    UncaughtExceptionHandler defaultUEH;

    public ExceptionHandler(Context con) {
        myContext = con;
        defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    }

    @SuppressWarnings("deprecation")
    public void uncaughtException(Thread thread, Throwable exception) {

        StringWriter stackTrace = new StringWriter();
        exception.printStackTrace(new PrintWriter(stackTrace));
        StringBuilder errorReport = new StringBuilder();
        errorReport.append("************ CAUSE OF ERROR ************\n\n");
        errorReport.append(stackTrace.toString());

        errorReport.append("\n************ DEVICE INFORMATION ***********\n");
        errorReport.append("Brand: ");
        errorReport.append(Build.BRAND);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("Device: ");
        errorReport.append(Build.DEVICE);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("Model: ");
        errorReport.append(Build.MODEL);
        errorReport.append(LINE_SEPARATOR);

        File root = android.os.Environment.getExternalStorageDirectory();
        String currentDateTimeString = DateFormat.getDateTimeInstance().format(
                new Date());

        File dir = new File(root.getAbsolutePath() + "/dir_name/log");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File file = new File(dir, "log.txt");

        try {
            BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
            buf.append(currentDateTimeString + ":" + errorReport.toString());
            buf.newLine();
            buf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        defaultUEH.uncaughtException(thread, exception);
        System.exit(0);
    }

}

1
给代码加一些解释。 - Sohil Desai
1
但是百万美元的问题是,“如何使用它??” - Shirish Herwade
谢谢,伙计,它正在运行。 - pranavjayadev
请指导一下!!Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));应该在onCreate()onResume()中调用。我的意思是哪个更好,我无法决定!如果我们在**onCreate()中调用它,那么ExceptionHandler将只被调用一次,如果在onResume()**中调用,则每次Activity进入前台时都会被调用。 - Pawan

5

我从 Stack Overflow 上得到了以下内容。你可以试一下:

public static void printLog(Context context){
    String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
    String command = "logcat -f "+ filename + " -v time *:V";

    Log.d(TAG, "command: " + command);

    try{
        Runtime.getRuntime().exec(command);
    }
    catch(IOException e){
        e.printStackTrace();
    }
}

此代码会持续打印日志直到应用退出。


创建空的 app_log 文件 .. ? - Strawberry
@strawberry> 你解决了这个问题吗? - Rashad
是的,我使用Thread.setDefaultUncaughtExceptionHandler解决了这个问题。 - Strawberry
@Strawberry 然后您可以接受帮助了您的答案... - Gopal Gopi

1
尝试这个:

    public void appendLog(String text) {       
        File logFile = new File("sdcard/log.file");
        if (!logFile.exists()) {
           try {
               logFile.createNewFile();
            } 
           catch (IOException e) {
               Log.e(TAG, e.getMessage(), e);
           }
        }
        try {
           //BufferedWriter for performance, true to set append to file flag
           BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
           buf.append(text);
           buf.newLine();
           buf.close();
        } catch (IOException e) {

           Log.e(TAG, e.getMessage(), e);
        }
    }

0

如果您只想捕获带有堆栈跟踪的异常,这通常足以找出问题所在,那么ACRA是一个胜利的解决方案。

如果您确实想要将某些内容写入SD卡,请注意您不能假设任何设备都有外部存储器可以写入,除非您已经验证了这一点。

为了提供另一种写入外部存储器的选择,您可以使用这个简单的库:
android-simple-storage

以下是使用方法:

  • 在你的应用程序中准备好某个地方:

    Storage storage = SimpleStorage.getExternalStorage();
    
    // 创建自己的目录
    storage.createDirectory("MyDir");
    
    // 在新目录中创建要写入的文件
    storage.createFile("MyDir", "MyFile.txt", "");
    
  • 无论何时,都可以将任何字符串(或字节数组)追加到此文件中:

    storage.appendFile("MyDir", "MyFile.txt", "your log line");
    

你可以使用这个小型库非常容易地在内部和外部存储器上创建/读取/更新/删除文件。请注意,对同一文件的写入将增加它所占用的空间。您可以使用同一库中的getSize()进行验证。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接