如何保持sysout和syserr流混合? [英] How to keep sysout and syserr streams from intermixing?

查看:348
本文介绍了如何保持sysout和syserr流混合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public static void main(String [] args){ 
System.out.println(启动应用程序);
try {
System.out.println(About to validate);
validate(args);
catch(Exception e){
e.printStackTrace();
}
}

public static void validate(String [] args){
System.out.println(你的第一个参数是+ args [0] );
if(someProblemWith(args)){
System.out.println(你的参数是错误的,应该是...);
抛出新的BadArgsException(e);
}
}

哪个工作正常。请注意,我上面的示例代码是有创造力的,仅仅是在异常和堆栈跟踪打印之前显示多个日志语句。这通常意味着我的最后一个日志记录语句在堆栈跟踪输出的中间丢失。有没有一个优雅的方式来询问 e.printStackTrace()语句等到System.out完成工作?我本质上正在寻找stacktrace作为错误发生时最后打印的东西。以下是我上面程序的输出示例:

  java.lang.Throwable 
....
at sun.reflect.NativeMethodAttributeImpl.invoke0
你的参数是错误的。应该是:...
在java.lang.reflect.Method.invoke(Method.java:597)
在org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java :56)


解决方案

致电 e .printStackTrace(的System.out); 。或者,如果您仅需要调试,您可以将进程的输出和错误与命令行分开: .... 1> output.log 2> error.log


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);
   }
}

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)

解决方案

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流混合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆