-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExceptionLogger.php
81 lines (69 loc) · 2.83 KB
/
ExceptionLogger.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
namespace Happyr\BrefMessenger;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;
use Symfony\Component\Messenger\Exception\HandlerFailedException;
use Symfony\Component\Messenger\Exception\ValidationFailedException;
use Symfony\Component\Validator\ConstraintViolationInterface;
class ExceptionLogger implements EventSubscriberInterface
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public static function getSubscribedEvents()
{
return [
WorkerMessageFailedEvent::class => ['onException', 20],
];
}
public function onException(WorkerMessageFailedEvent $event)
{
$envelope = $event->getEnvelope();
$throwable = $event->getThrowable();
$firstNestedException = null;
if ($throwable instanceof HandlerFailedException) {
$envelope = $throwable->getEnvelope();
$nestedExceptions = $throwable->getNestedExceptions();
$firstNestedException = $nestedExceptions[array_key_first($nestedExceptions)];
}
if ($throwable instanceof ValidationFailedException) {
$this->logValidationException($throwable);
} else {
$this->logException($envelope, $throwable, $event->getReceiverName(), $firstNestedException);
}
}
private function logValidationException(ValidationFailedException $exception): void
{
$violations = $exception->getViolations();
$violationMessages = [];
/** @var ConstraintViolationInterface $v */
foreach ($violations as $v) {
$violationMessages[] = \sprintf('%s: %s', $v->getPropertyPath(), (string) $v->getMessage());
}
$this->logger->error('{class} did failed validation.', [
'class' => get_class($exception->getViolatingMessage()),
'violations' => \json_encode($violationMessages),
]);
}
private function logException(Envelope $envelope, \Throwable $throwable, string $transportName, ?\Throwable $firstNestedException): void
{
$message = $envelope->getMessage();
$context = [
'exception' => $throwable,
'message' => $message,
'transport' => $transportName,
'class' => \get_class($message),
];
if (null === $firstNestedException) {
$logMessage = 'Dispatching {class} caused an exception: '.$throwable->getMessage();
} else {
$logMessage = 'Handling {class} caused an HandlerFailedException: '.$throwable->getMessage();
$context['first_exception'] = $firstNestedException;
}
$this->logger->error($logMessage, $context);
}
}