【问题标题】:How to include current date when logging exceptions to a file with FileOutputStream?使用 FileOutputStream 将异常记录到文件时如何包含当前日期?
【发布时间】:2018-05-08 06:48:06
【问题描述】:

我已经实现了一种将日志写入文件的方法。它工作正常。现在我想弄清楚是否有办法在记录的异常中包含当前日期/时间,如 (new java.util.Date().toString())?

 private static void writeLogToFile(Exception e) {
        try (FileOutputStream fos = new FileOutputStream(LOG_FILE, true);
             PrintStream printStream = new PrintStream(fos)) {
             e.printStackTrace(printStream);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

目前以这种方式记录异常:

} catch (Exception e) {
            writeLogToFile(e);
        }

我知道日志框架,在这种情况下故意不使用它们。

【问题讨论】:

  • 你为什么故意自己写一个糟糕的记录器?有什么优势?
  • @Kayaman 我只是在学习,抱歉。没有理由拒绝投票。

标签: java exception logging io


【解决方案1】:

你应该看看SimpleDateFormat。它提供了您需要的功能! (日期转字符串)


我在您的代码中看到的另一件事是:您每次写日志时都会打开FileOutputStream

最好将流保存在全局变量中,而不是每次记录某些内容时打开/关闭它


结果可能有点像这样:

// open/close the stream in some kind of static init()/deinit() method
private static PrintStream logStream;
private static SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd_HH-mm-ss: ");

private static void writeLogToFile(Exception e) {
    logStream.println(sdf.format(new Date()) + e.getMessage());
    e.printStackTrace(logStream);
}

【讨论】:

  • 我添加了一些小的示例代码(当然,您必须根据自己的需要进行调整)
  • 谢谢它真的帮助我更好地理解它。
  • 随时!但是,如果您的程序完成,请不要忘记关闭流!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 2013-10-17
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
  • 2014-07-04
相关资源
最近更新 更多