简体   繁体   English

如何将异常的StackTrace附加到java中的文件中?

[英]How to append an exception's StackTrace into a file in java?

In java, when we catch a exception, we usually can use printStackTrace() method to print the error information, and we can also use printStackTrace(PrintStream out) to direct those information to a file. 在java中,当我们捕获异常时,我们通常可以使用printStackTrace()方法来打印错误信息,我们也可以使用printStackTrace(PrintStream out)将这些信息printStackTrace(PrintStream out)文件。

But how can I append those information into a existing file, just like using out.append() ? 但是,如何将这些信息附加到现有文件中,就像使用out.append()

You must open file in append mode: 您必须以追加模式打开文件:

try {
    //...
} catch (Exception e) {
    try(Writer w = new FileWriter("file.log", true)) {
        e.printStackTrace(new PrintWriter(new BufferedWriter(w)));
    }
}

If you are not using Java 7, you must remember about closing or at least flushing the Writer . 如果您不使用Java 7,则必须记住关闭或至少刷新Writer Or you can have a global Writer , but then you must synchronize it between threads. 或者你可以有一个全局的Writer ,但是你必须在线程之间同步它。

What about simply using some existing Java library like , or even java.util.logging ? 如何简单地使用一些现有的Java库,如甚至java.util.logging Simply say: 简单地说:

} catch (Exception e) {
    log.error("Opps!", e);
}

...and the framework will log the exception wherever you want, with lots of additional data like thread name, timestamp, additional message, etc. Logback can also show you from which library given stack frame comes from and even print the stack trace starting from root cause (most nested exception). ...并且框架将在任何地方记录异常,包含许多其他数据,如线程名称,时间戳,附加消息等。回溯还可以显示给定堆栈帧来自哪个库,甚至打印堆栈跟踪开始从根本原因(大多数嵌套异常)。

We can redirect the error stream to a file 我们可以将错误流重定向到文件

System.setErr(new PrintStream(new FileOutputStream("errors.txt", true), true));

then Throwable.printStackTrace() will print to errors.txt. 然后Throwable.printStackTrace()将打印到errors.txt。

"true" in FileOutputStream constructor means "append"; FileOutputStream构造函数中的“true”表示“追加”; "true" in PrintStream condtructor means "autoflush". PrintStream condtructor中的“true”表示“autoflush”。 We do not need to worry about never closing FileOutputStream, OS will close it when the app ends. 我们不需要担心永远不会关闭FileOutputStream,操作系统会在应用程序结束时关闭它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM