简体   繁体   English

将所有System.out写入文件

[英]Write all System.out into a file

I have a large program in which I have used System.out for debugging. 我有一个大型程序,我使用System.out进行调试。 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. 但我希望能够将所有System.out同时记录到一个文件中,所以即使我的程序没有在控制台中运行,所有System.out都会写入文件,我将能够看到它程序运行或以后的任何时刻。

Btw, it's not wise to crawl all the program and use a logger instead of System.out statements! 顺便说一句,抓取所有程序并使用记录器而不是System.out语句是不明智的!

I tried java -jar myjar.jar > sysout.txt but it doesn't log the exceptions logged by java logger utility. 我尝试了java -jar myjar.jar > sysout.txt但它没有记录java logger实用程序记录的异常。

What about System.setOut(PrintStream) ? 那么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. 当然,您可以使用System.err(即System.setErr(PrintStream))执行相同操作,但最好使用不同的文件流。

In detail assuming an autoflushing appending and buffered file stream: 详细假设一个autoflushing附加和缓冲文件流:

    String file = ...;
    PrintStream ps = 
      new PrintStream(true, new BufferedOutputStream(new FileOutputStream(file, true)));
    System.setOut(ps);

The normal redirection command_name args > output only redirect Standard Output. 正常重定向command_name args > outputcommand_name args > 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 请在http://www.tldp.org/LDP/abs/html/io-redirection.html上查看更多选项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM