How to keep sysout and syserr threads from mixing?

My code base has (very simplified) the 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 great. Please note that my sample code above was invented and just designed to display multiple log statements before printing the exception trace and stack trace. This often means that my last log statement is lost in the middle of the stack trace output. Is there an elegant way to ask the operator e.printStackTrace()to wait for System.out to complete its work? I am essentially looking for stacktrace to be the very last thing printed when an error occurs. Here is an example of the 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)
+3
source share
2

e.printStackTrace(System.out);. , , : .... 1>output.log 2>error.log

+1

, System.out.println(), , System.out , System.err ( ) .

, , , "unbuffer" System.out. - System.err System.out.

System.out.flush() , catch.

2: Logger.

3. "". , , ( .toString() , ), catch, . ( , System.out).

- == -

FROM COMMENT

. Logger . . Logger Logger ( ), , . .log(). Logger , ( DEBUG, WARN...), / , . "" , , :

2010-11-23 14:45:32,032 DEBUG [MyClass] Your message

log4j, Java Logger. , , . , .

+8

Source: https://habr.com/ru/post/1776435/


All Articles