Monolog 不接受 Crunz 回调中的严重错误

Monolog does not accept critical error in Crunz callback

我正在使用 Crunz 来触发任务。在此任务中,我成功地记录了信息。

尝试在回调函数中记录严重错误时,出现错误。 日志提到:

[2020-09-16T11:36:24.050666+00:00] MyLogger.CRITICAL: Critical error has occurred (works) [] []
[2020-09-16T11:36:25.343237+00:00] MyLogger.INFO: Performed A [] []
[2020-09-16T11:36:25.420212+00:00] Crunz.ERROR: XXX(object(Closure))   Fatal error: Uncaught Error: Call to a member function setFormatter() on null in /vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php on line 126

我的 Crunz 任务的代码如下:

<?php

declare(strict_types=1);

namespace My\Custom\Name;

use Crunz\Schedule;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Handler\SlackWebhookHandler;

$logger = new Logger('MyLogger');
$logger->pushHandler(
    new StreamHandler(
        customlogsPath() . '/jobs.log',
        Logger::INFO
    )
);
// Slack
$logger->pushHandler(
    new SlackWebhookHandler(
        'SLACK_WEBHOOK_URL',
        'SLACK_CHANNED',
        'someUsername',
        true,
        'red_circle',
        false,
        false,
        Logger::CRITICAL
    )
);

$logger->critical('Critical error has occurred (works)');

$schedule = new Schedule();
$task = $schedule->run(function () use ($logger) {
    $myArray = [
        1 => 'test'
    ];

    foreach ($myArray as $item) {
        $scheduled = true;

        if ($scheduled) {
            // Do a
            $logger->info('Performed A');
        } else {
            // Do B
            $logger->info('Performed B');
        }
    }

    $logger->critical('Critical error (does not work)');
});
$task
    ->description('XXX')
    ->preventOverlapping()
    ->everyMinute()
;

return $schedule;

正如您在上面看到的,critical 日志在回调函数外部定义时确实有效。我也在 Slack 中收到了这条消息。

当我在 Crunz 回调中定义 pushHandler 时,它得到了正确处理,没有任何错误。显然,在回调中使用 $logger 是不够的。