我没有一个 windows 框来测试这个,但也许你可以做一些事情,比如制作一个绑定句柄,它将打印到 STDOUT 和日志,然后将 STDOUT 和 STDERR 重定向到它?
编辑:我唯一担心的是存储 STDOUT 以供以后使用的方法,如果第一种在 Windows 上不起作用,我添加了第二种可能性来存储 STDOUT 以供以后使用。他们都在 Linux 上为我工作。
#!/usr/bin/perl
use strict;
use warnings;
tie *NEWOUT, 'MyHandle', 'test.log';
*STDOUT = *NEWOUT;
*STDERR = *NEWOUT;
print "Print\n";
warn "Warn\n";
package MyHandle;
sub TIEHANDLE {
my $class = shift;
my $filename = shift;
open my $fh, '>', $filename or die "Could not open file $filename";
## Use one of these next two lines to store STDOUT for later use.
## Both work for me on Linux, if one does not work on Windows try the other.
open(OLDSTDOUT, '>&STDOUT') or die "Could not store STDOUT";
#*OLDSTDOUT = *STDOUT;
my $self = {
loghandle => $fh,
logfilename => $filename,
stdout => \*OLDSTDOUT,
};
bless $self, $class;
return $self;
}
sub PRINT {
my $self = shift;
my $log = $self->{loghandle};
my $stdout = $self->{stdout};
print $log @_;
print $stdout @_;
}