Is there any way I can save all the things that is happening on my Windows 7 Command Prompt in a file. So that I can see what are the things that got printed on the console. I am running a multithreaded Java Program from the command prompt as-
java -server -Xms512m -Xmx512m -XX:PermSize=512m -XX:MaxPermSize=512m -Duser.timezone=GMT-7 –jar BatchMain.jar -taskId V3-PERSONALIZATIONGEO-SAMPLE-TASK -noofthreads 1 -timeout 5 -numberOfIP 1000 -privateIPAddress false
And it prints lot of things on to the command prompt, And I want to store all these things that are getting printed on the console into a file.
You can either capture the output directly in your program, or on the console.
On the console
If you want to get absolutely everything (both STDOUT and STDERR), you need to redirect STDOUT (from System.out) and STDERR (from System.err). You can either redirect both to the same file (add
> log.txt 2>&1to the end of your console command), or you can log them to different files (add> BatchMain.log 2> BatchMain.errto the end of your console).Log to a single file, log.txt:
Log to separate files, BatchMain.log and BatchMain.err:
Directly within your program
In your
main(String[] args)method (or some other appropriate place), set System.out and System.err to print directly to files (or the same file, if you wish). For example:If you want the output to also be visible on the console, you can go a step further and insert your own intermediate PrintStream which does this.
Other things to consider
Note that Java buffers System.out, so if you log both STDOUT and STDERR to the same file, you could end up with nonsensical output that has the two PrintStreams interwoven, or something in STDOUT could be printed much later than a related message that was printed to STDERR. One workaround is to call
System.out.flush()as appropriate, but this could degrade performance if you’re logging a lot of text toSystem.out.Rather than printing everything to the console with
System.out.println()and trying to capture that output, I’d recommend using Java Logging or Log4J, or going a step further and using Apache Commons Logging, which can be configured to use either of the first two systems internally. The really awesome part is that you don’t have to divine which class printed each log message, because you’ll get that automatically.If you use a logging framework, you can also adjust the verbosity of your logging output by setting a single variable–which will come in handy at release time.