我想保留控制台显示输出,但也将其作为日志保存在文本文件中。有什么办法可以做到这一点吗?我尝试这样做:
PrintStream printStream = new PrintStream(new FileOutputStream(locations[0][0] + "-" + locations[0][1] + "-output.txt"));
System.setOut(printStream);
但它不再在控制台中显示输出,而是将其保存在项目目录中。有没有办法同时做到这两点?
您需要使用写入两个目标流(文件和 stdio)的流。例如,使用 Apache 的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));
另一种选择(在 JAVA 范围之外)是使用 *nix tee
工具:
java -cp ... com.package.MyClass | tee /var/log/myapp/mylogfile.txt