Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write all System.out into a file

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.

like image 891
Johnny Avatar asked Jan 11 '23 13:01

Johnny


1 Answers

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);
like image 147
Meno Hochschild Avatar answered Jan 22 '23 21:01

Meno Hochschild