我不仅需要将我的消息记录到系统日志中(据我所知,系统日志缓冲区非常短,但我需要查看3-5天的日志),而且还需要在一个单独的文本文件中。日志记录必须是异步的。你能给我一个关于在这种情况下我应该使用哪个组件的建议吗?谢谢。
发布于 2018-04-20 18:41:03
我希望它能对你有用。
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的权限!
发布于 2018-04-20 19:17:07
异步工作,不需要权限!
只需记住在onCreateMethod中调用应用程序中的初始化方法即可初始化记录器
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();
                }
            }
        });
    }
}你也可以用Timber库做同样的事情,以获得更多信息:
https://medium.com/@vicky7230/file-logging-with-timber-4e63a1b86a66
https://stackoverflow.com/questions/49939695
复制相似问题