在安卓中登录文本文件



我不仅需要将我的消息记录到系统日志中(据我所知,系统日志缓冲区很短,但我需要查看 3-5 天的日志(,还需要在单独的文本文件中。日志记录必须是异步的。您能给我一个关于在这种情况下应该使用哪个组件的建议吗?谢谢。

我希望它对您有用。

public void appendLog(String text) {
    File logFile = new File("sdcard/log.file");
    if (!logFile.exists()) {
        try {
            logFile.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    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) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

不要忘记在清单中添加android.permission.WRITE_EXTERNAL_STORAGE权限!

异步工作,不需要许可!

只要记住在onCreateMethod中从你的应用程序调用init方法来初始化记录器

class Logger {

    private static File logFileLoc;
    private static ExecutorService logExecutor;
    public static void init(Context applicationContext, String logFileName, boolean reCreate) {
        logFileLoc = new File(applicationContext.getCacheDir(), logFileName);
        if (reCreate && logFileLoc.exists()) logFileLoc.delete();
        logExecutor = Executors.newSingleThreadExecutor();
    }
    public static void log(final String tag, final String msg) {
        if (logFileLoc == null) try {
            throw new Exception("First you should call init method in your application");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d(tag, msg);

        logExecutor.execute(new Runnable() {
            @Override
            public void run() {

                try {
                    BufferedWriter writer = new BufferedWriter(new FileWriter(logFileLoc,true));
                    String timeStamp = DateFormat.getDateTimeInstance().format(new Date(System.currentTimeMillis()));
                    writer.append(timeStamp + "  " + tag + "  : " + msg );
                    writer.newLine();
                    writer.flush();
                    writer.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

您也可以对木材库做同样的事情以获取更多信息:

https://medium.com/@vicky7230/file-logging-with-timber-4e63a1b86a66

相关内容

  • 没有找到相关文章

最新更新