CakePHP:如果发生至少1个错误,则通过电子邮件发送日志记录输出

时间:2018-08-14 10:33:03

标签: cakephp

我有一个基于CakePHP 3.6的控制台应用程序。只要日志记录中至少包含一个错误或警告,它就会自动发送电子邮件。为此有记录仪吗?

2 个答案:

答案 0 :(得分:0)

由于找不到任何内容,我创建了一个自定义记录器,将日志条目保存在类变量中:

<?php
namespace App\Log\Engine;
use Psr\Log\LogLevel;

use Cake\Log\Engine\BaseLog;

class BufferLog extends BaseLog
{
    protected static $buffer = '';

    protected static $needsSending = false;

    public static function getBuffer() {
        if (self::$needsSending)
            return self::$buffer;
        return '';
    }

    public static function reset() {
            self::$buffer = false;
            self::$needsSending = false;
    }

    public function log($level, $message, array $context = [])
    {
        $alert = [
            LogLevel::EMERGENCY,
            LogLevel::CRITICAL,
            LogLevel::ALERT,
            LogLevel::ERROR,
            LogLevel::WARNING,
        ];
        if (in_array($level, $alert)) {
            self::$needsSending = true;
        }

        $message = $this->_format($message);

        unset($context['scope']);
        if ($context) {
            $message .= "\n" . $this->_format($context) . "\n";
        }

        self::$buffer .=  date('c') . ' [' . $level . '] ' . $message . "\n";
    }
}

然后,在外壳程序Command结束时,如果需要,它将发送电子邮件:

$logOutput = BufferLog::getBuffer();
if ($logOutput) {
    Email::deliver('you@example.com', 'Log', $logOutput, ['from' => 'me@example.com']);
}

(请注意,这仅适用于日志文件中的错误,不适用于PHP错误。)

答案 1 :(得分:0)

如果您想记录PHP错误,可以使用一个插件来实现:

https://github.com/ebrigham1/cakephp-error-email