2020-11-02 22:45:37 +08:00
|
|
|
<?php
|
|
|
|
declare(strict_types=1);
|
2021-09-04 20:18:20 +08:00
|
|
|
|
2020-11-02 22:45:37 +08:00
|
|
|
/**
|
|
|
|
* This file is part of Hyperf.
|
|
|
|
*
|
|
|
|
* @link https://www.hyperf.io
|
|
|
|
* @document https://hyperf.wiki
|
|
|
|
* @contact group@hyperf.io
|
|
|
|
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
|
|
|
|
*/
|
2021-04-20 16:30:57 +08:00
|
|
|
|
2020-11-02 22:45:37 +08:00
|
|
|
namespace App\Listener;
|
|
|
|
|
|
|
|
use Hyperf\AsyncQueue\Event\AfterHandle;
|
|
|
|
use Hyperf\AsyncQueue\Event\BeforeHandle;
|
|
|
|
use Hyperf\AsyncQueue\Event\Event;
|
|
|
|
use Hyperf\AsyncQueue\Event\FailedHandle;
|
|
|
|
use Hyperf\AsyncQueue\Event\RetryHandle;
|
|
|
|
use Hyperf\Event\Annotation\Listener;
|
|
|
|
use Hyperf\Event\Contract\ListenerInterface;
|
|
|
|
use Hyperf\ExceptionHandler\Formatter\FormatterInterface;
|
|
|
|
use Hyperf\Logger\LoggerFactory;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @Listener
|
|
|
|
*/
|
|
|
|
class QueueHandleListener implements ListenerInterface
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @var \Psr\Log\LoggerInterface
|
|
|
|
*/
|
|
|
|
protected $logger;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @var FormatterInterface
|
|
|
|
*/
|
|
|
|
protected $formatter;
|
|
|
|
|
|
|
|
public function __construct(LoggerFactory $loggerFactory, FormatterInterface $formatter)
|
|
|
|
{
|
2021-04-20 16:30:57 +08:00
|
|
|
$this->logger = $loggerFactory->get('queue');
|
2020-11-02 22:45:37 +08:00
|
|
|
$this->formatter = $formatter;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function listen(): array
|
|
|
|
{
|
|
|
|
return [
|
|
|
|
AfterHandle::class,
|
|
|
|
BeforeHandle::class,
|
|
|
|
FailedHandle::class,
|
|
|
|
RetryHandle::class,
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
public function process(object $event)
|
|
|
|
{
|
|
|
|
if ($event instanceof Event && $event->message->job()) {
|
2021-04-20 16:30:57 +08:00
|
|
|
$job = $event->message->job();
|
2020-11-02 22:45:37 +08:00
|
|
|
$jobClass = get_class($job);
|
2021-04-20 16:30:57 +08:00
|
|
|
$date = date('Y-m-d H:i:s');
|
2020-11-02 22:45:37 +08:00
|
|
|
|
|
|
|
switch (true) {
|
|
|
|
case $event instanceof BeforeHandle:
|
|
|
|
$this->logger->info(sprintf('[%s] Processing %s.', $date, $jobClass));
|
|
|
|
break;
|
|
|
|
case $event instanceof AfterHandle:
|
|
|
|
$this->logger->info(sprintf('[%s] Processed %s.', $date, $jobClass));
|
|
|
|
break;
|
|
|
|
case $event instanceof FailedHandle:
|
|
|
|
$this->logger->error(sprintf('[%s] Failed %s.', $date, $jobClass));
|
|
|
|
$this->logger->error($this->formatter->format($event->getThrowable()));
|
|
|
|
break;
|
|
|
|
case $event instanceof RetryHandle:
|
|
|
|
$this->logger->warning(sprintf('[%s] Retried %s.', $date, $jobClass));
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|