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 流混合?


- 如何使用WebFilter实现授权头检查 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01