4

I have a large program in which I have used System.out for debugging. But I'd like to be able to log all System.out simultaneously to a file so even if my program isn't run in the console all the System.out will be written to a file and I will be able to see it in any moment the program is running or later.

Btw, it's not wise to crawl all the program and use a logger instead of System.out statements!

I tried java -jar myjar.jar > sysout.txt but it doesn't log the exceptions logged by java logger utility.

Johnny
  • 1,509
  • 5
  • 25
  • 38

2 Answers2

5

What about System.setOut(PrintStream) ? You could insert this call in the initialization part of your program (start-up).

Was previously a commment:

And of course you can do the same with System.err - namely System.setErr(PrintStream), but better to a different file stream.

In detail assuming an autoflushing appending and buffered file stream:

    String file = ...;
    PrintStream ps = 
      new PrintStream(true, new BufferedOutputStream(new FileOutputStream(file, true)));
    System.setOut(ps);
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
  • 1
    And of course you can do the same with `System.err` - namely `System.setErr(PrintStream)`, but better to a different file stream. – Meno Hochschild Jan 02 '14 at 18:24
  • I think it is better if you edited your answer to include the details of your comment above. That would make it a more complete answer. :) – Buddhima Gamlath Jan 02 '14 at 18:36
4

The normal redirection command_name args > output only redirect Standard Output. It does not redirect Standard Error stream, where usually the errors are logged in. To output both streams to the same file use,

command args &> filename

eg. java -jar myjar.jar &> sysout.txt

To redirect to different files, use

command args 1> output_file 2> error_file

eg. java -jar myjar.jar 1> sysout.txt 2> errout.txt

See more options at http://www.tldp.org/LDP/abs/html/io-redirection.html

Buddhima Gamlath
  • 2,318
  • 1
  • 16
  • 26
  • 1
    excellent! That's very nice however I find the Meno Hochschild's answer more flexible because it is Java-ish and I will be able to make daily dev logs! – Johnny Jan 02 '14 at 18:31
  • @Johnny: Yup, that way you do not have to rely on the execution commands. :) – Buddhima Gamlath Jan 02 '14 at 18:37