How to redirect JVM output without tear up output from the application?
Question: Recently I am writing some micro-benchmark code, so I have to print out the
JVM behaviors along with my benchmark information. I use

    
    
    -XX:+PrintCompilation
    -XX:+PrintGCDetails
    

and other options to get the JVM status. For benchmark information, I simply
use `System.out.print()` method. Because I need to know the order of the
message I printed and the JVM output.

I can get good result when I just print them out in the console, although the
JVM output sometimes tear my messages up, but since they are in different
threads, it is understandable and acceptable.

When I need to do some batch benchmarks, I'd like to _**`redirect the output
into a file`**_ with `pipe (> in Linux system)`, and use python to get the
result from the file and analyse it.

Here is the problem:

**`The JVM output always overlapped with the messages I printed in the Java
application.`** It ruined the completion of the messages.

Any idea how to deal with this situation? I need **`both the JVM output and
application output in the same place in order to preserve the sequence because
it is important. And they do not overlap on each other so I don't lose
anything.`**


Answer: I would suggest taking a slight detour and looking at using Java
Instrumentation APIs - use (write) a simple **Java Agent** to do this. From
your benchmarking perspective, this will give you far more power as well. You
could use your Java Agent to log everything (and hence there would be no
contention between different logger threads).

You can read more at <http://www.javabeat.net/2012/06/introduction-to-java-
agents/> or <http://today.java.net/pub/a/today/2008/04/24/add-logging-at-
class-load-time-with-instrumentation.html>

