How to keep sysout and syserr streams from intermixing?(如何防止 sysout 和 syserr 流混合?)
问题描述
在我的代码库中(非常简化)如下:
In my code base is the (very simplified) following:
public static void main (String[] args) {
System.out.println("Starting application");
try {
System.out.println("About to validate");
validate(args);
catch (Exception e) {
e.printStackTrace();
}
}
public static void validate(String[] args) {
System.out.println("Your first arg is " + args[0]);
if (someProblemWith(args)) {
System.out.println("Your args are wrong. It should be: ...");
throw new BadArgsException(e);
}
}
哪个工作正常.请注意,我上面的示例代码是人为设计的,只是为了在异常和堆栈跟踪打印之前显示多个日志语句.这通常意味着我的最后一条日志语句在堆栈跟踪输出的中间丢失了.有没有一种优雅的方式让 e.printStackTrace()
语句等待 System.out 完成它的工作?我本质上是在寻找堆栈跟踪作为发生错误时打印的最后一件事.这是我上面程序的示例输出:
Which works fine. Note that my example code above is contrived and simply meant to show multiple log statements prior to exception and stack trace printing. This often means that my last logging statement is lost in the middle of the stack trace output. Is there an elegant way to ask the e.printStackTrace()
statement to wait until the System.out has finished its work? I'm essentially looking for the stacktrace to be the very last thing printed when an error occurs. Here's a sample output of my program above:
java.lang.Throwable
....
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
Your args are wrong. It should be: ...
at java.lang.reflect.Method.invoke(Method.java:597)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:56)
推荐答案
调用e.printStackTrace(System.out);
.或者,如果您只需要它用于调试,您可以将进程的输出和错误与命令行分开:.... 1>output.log 2>error.log
Call e.printStackTrace(System.out);
. Or, if you need it for debugging only, you can separate the process' output and error from the command line: .... 1>output.log 2>error.log
这篇关于如何防止 sysout 和 syserr 流混合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何防止 sysout 和 syserr 流混合?


基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01