gpt4 book ai didi

perl - 如何将STDOUT和STDERR重定向到Perl中的日志文件?

转载 作者:行者123 更新时间:2023-12-04 09:43:12 26 4
gpt4 key购买 nike

这个问题已经在这里有了答案:




已关闭10年。




Possible Duplicate:
Can I send STDOUT and STDERR to a log file and also to the screen in Win32 Perl?



我想将STDOUT,STDERR重定向到temp_log,然后在该过程完成后重定向到logfile.txt。该过程运行了20分钟,因此我想在运行过程中将temp_log聚集起来。

最佳答案

STDOUTSTDERR只是被初始化为程序的标准输出和错误的文件句柄,但可以出于任何原因随时重新分配它们。为此,您将要保存原始设置,以便可以还原它们。

sub process_that_writes_to_temp_log {

# save original settings. You could also use lexical typeglobs.
*OLD_STDOUT = *STDOUT;
*OLD_STDERR = *STDERR;

# reassign STDOUT, STDERR
open my $log_fh, '>>', '/logdirectory/the-log-file';
*STDOUT = $log_fh;
*STDERR = $log_fh;

# ...
# run some other code. STDOUT/STDERR are now redirected to log file
# ...

# done, restore STDOUT/STDERR
*STDOUT = *OLD_STDOUT;
*STDERR = *OLD_STDERR;
}

根据程序的布局方式,可以使用 local自动完成保存和恢复旧的STDOUT/STDERR设置。
sub routine_that_writes_to_log {
open my $log_fh, '>>', 'log-file';
local *STDOUT = $log_fh;
local *STDERR = $log_fh;

# now STDOUT,STDERR write to log file until this subroutine ends.
# ...

}

关于perl - 如何将STDOUT和STDERR重定向到Perl中的日志文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3822787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com