perl - 从其他类方法重定向打印流

标签 perl oop logging

假设我有一个父类和一个子类。 我只能修改 Child 类。

父类中有一些print

package Parent;

use strict;
use warnings;

sub new
{
    my $class = shift;
    my $self = {};
    bless $self, $class;
    return $self;
}

sub sayHello{
    my $self = shift;
    print "Hello world\n";
}

sub sayBye{
    my $self = shift;
    print "Bye world\n";
}

1;

在我的 Child 类中,我有一个将内容打印到日志文件中的方法。

package Child;

use strict;
use warnings;

use parent 'Parent';

sub new
{
    my $class = shift;
    my $self = $class->SUPER::new();
    return $self;
}

sub talk{
    my $self = shift;
    $self->sayHello;
    $self->sayBye;
}

sub talkToLog{
    my $self = shift;

    my $logName = 'file.log';

    $self->log($logName, $self->sayHello); # Here's my best (not working) try
    $self->log($logName, $self->sayBye);
}

sub log{
    my $self = shift;
    my $filename = shift;
    my $string = shift;
    open(my $fh, ">>", $filename) || die "Couldn't open file $filename: $!";
    print $fh $string;
    close $fh;
    return;
}

1;

问题:是否有某种方法可以“捕获”来自 Child 类的这些打印流并使用 log 方法记录该内容?


这是我用来尝试的 pl 文件。

#!/usr/bin/perl

use strict;
use warnings;

use Child;
my $child = Child->new;

$child->talk;
$child->talkToLog;

它在控制台中打印:

Hello world
Bye world
Hello world
Bye world

最佳答案

你需要这样的东西:

sub talkToLog{
    my $self = shift;

    my $logName = 'file.log';
    my $output = '';

    open TOOUTPUT, '>', \$output or die "Can't open TOOUTPUT: $!";
    select TOOUTPUT;

    $self->sayHello;
    $self->log($logName, $output);

    $output = '';
    $self->sayBye;
    $self->log($logName, $output);

    select STDOUT;
}

关于perl - 从其他类方法重定向打印流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46298535/

相关文章:

laravel - 为什么 Laravel 中间件会被执行多次?

Django 中的 Python 日志记录

.net - 排查 App Insight 仅显示部分日志的问题

perl - 使用 Perl 拉伸(stretch)、调整大小或缩略图

c++ - 从 linux 命令行用另一个替换整个段落

java - 从 Java 启动的 Perl 需要永远

java - getResources 作为全局变量

php - 在另一个 PHP 类中使用许多不同的对象实例的最佳方法是什么?

regex - Perl:($num) 和 $num 之间的区别

C#:继承、覆盖和隐藏