在没有输出缓冲的情况下复制输出

Copy output without output buffering

我有一个 PHP 脚本,可以将一些日志、错误等写入 consol

我想将所有这些信息保存到一个变量中,以便在执行结束时发送电子邮件。

我知道我可以使用 obstart 和 co 来做到这一点,但我也希望在执行期间日志显示 实时。所以我不认为输出缓冲是我的问题的解决方案,但我没有看到其他解决方案。

请问有什么办法吗?

提前致谢

您将不得不想出某种自定义记录器,除了将消息输出到控制台外,还会在脚本关闭时发送电子邮件。像这样:

interface MailerInterface {
    function send($recipient, $title, $body);
}

interface LoggerInterface {
    function log($message);
}

class ConsoleLoggerWithMailer implements LoggerInterface {

    /**
     * @var string[]
     */
    private $messages = array();

    /**
     * @var MailerInterface
     */
    private $mailer;

    /**
     * @var string
     */
    private $recipient;

    public function __construct() {
        register_shutdown_function(array($this, 'sendMessages'));
    }

    /**
     * @param MailerInterface $mailer
     * @param string $recipient
     */
    public function setMailer(MailerInterface $mailer, $recipient) {
        $this->mailer = $mailer;
        $this->recipient = $recipient;
    }

    /**
     * @return string[]
     */
    public function getMessages() {
        return $this->messages;
    }

    public function log($message) {
        $this->messages[] = $message;

        printf("%s\n", $message);
    }

    public function sendMessages() {
        if ($this->mailer === null || count($this->messages) === 0)
            return;

        $this->mailer->send($this->recipient, 'log', implode("\n", $this->messages));
    }
}

使用示例假设您还创建了一些实现 MailerInterface 的 Mailer class:

$mailer = new Mailer();
$logger = new ConsoleLoggerWithMailer();
$logger->setMailer($mailer, "webmaster@example.com");

$logger->log("Starting...");
$logger->log("Doing...");
$logger->log("End");