gpt4 book ai didi

perl - CGI : Redirecting STDERR to file with an alteration

转载 作者:行者123 更新时间:2023-12-01 13:13:24 25 4
gpt4 key购买 nike

STDERR 重定向到外部文件非常简单

my $stderr = '/home/logs/stderr.log.txt';
open STDERR, '>' . $stderr;
...
$_ = 1/0; # Error: Illegal division by zero

为了使这个错误日志文件更具可读性,我想在每次发送到 STDERR添加时间戳信息。

那怎么能做到呢?

最佳答案

对其余代码没有太多干扰的最简单方法是使用绑定(bind)文件句柄。绑定(bind)文件句柄允许您编写自定义函数,当您的文件句柄被读取、写入或对其执行任何其他操作时调用这些函数。

概念验证

package TimeStamper;
sub TIEHANDLE {
my ($pkg,$file) = @_;
open my $fh, ">", $file; # the "real" filehandle
return bless [$fh],$pkg;
}
sub PRINT {
my ($self,@msg) = @_;
print {$self->[0]} "[",scalar localtime,"] ",@msg;
}

package main;
my $stderr = "/home/logs/stderr.log.txt";
tie *STDERR, "TimeStamper", $stderr;

print STDERR "Hello world\n";

关于perl - CGI : Redirecting STDERR to file with an alteration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58345462/

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