How do I save the console output to a textfile in a certain directory?

139 Views Asked by At

I'd like to keep the console displaying the output but also keep it in a textfile as a log. Is there any way to do this? I tried doing this:

PrintStream printStream = new PrintStream(new FileOutputStream(locations[0][0] + "-" + locations[0][1] + "-output.txt"));
System.setOut(printStream);

But it doesn't display the output in the console anymore and it saves it in the project directory. Is there a way to do both?

1

There are 1 best solutions below

4
On

You need to use a stream which writes to two destination streams (file and stdio). For example, use Apache's TeeOutputStream:

// Directory to save log files in
File logDir = new File("/var/log/myapp");
// Name of log file
String logFileName = locations[0][0] + "-" + locations[0][1] + "-output.txt";
// Actual log file
File logFile = new File(logDir, logFileName);

// File stream
OutputStream fileStream = new FileOutputStream(logFile);
// Stdout
OutputStream stdioStream = System.out;
// A stream redirecting output to both supplied streams
OutputStream combinedStream = new TeeOutputStream(stdioStream, fileStream);
// Finally use the resulting stream
System.setOut(new PrintStream(combinedStream));

Another alternative (out of the JAVA scope) is to use the *nix tee tool:

java -cp ... com.package.MyClass | tee /var/log/myapp/mylogfile.txt