3 namespace Drupal\Core\EventSubscriber;
5 use Drupal\Core\Logger\LoggerChannelFactoryInterface;
6 use Drupal\Core\Utility\Error;
7 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
8 use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
9 use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
10 use Symfony\Component\HttpKernel\KernelEvents;
13 * Log exceptions without further handling.
15 class ExceptionLoggingSubscriber implements EventSubscriberInterface {
18 * The logger channel factory.
20 * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
25 * Constructs a new ExceptionLoggingSubscriber.
27 * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger
28 * The logger channel factory.
30 public function __construct(LoggerChannelFactoryInterface $logger) {
31 $this->logger = $logger;
37 * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
38 * The event to process.
40 public function on403(GetResponseForExceptionEvent $event) {
41 $request = $event->getRequest();
42 $this->logger->get('access denied')->warning('@uri', ['@uri' => $request->getRequestUri()]);
48 * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
49 * The event to process.
51 public function on404(GetResponseForExceptionEvent $event) {
52 $request = $event->getRequest();
53 $this->logger->get('page not found')->warning('@uri', ['@uri' => $request->getRequestUri()]);
57 * Log not-otherwise-specified errors, including HTTP 500.
59 * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
60 * The event to process.
62 public function onError(GetResponseForExceptionEvent $event) {
63 $exception = $event->getException();
64 $error = Error::decodeException($exception);
65 $this->logger->get('php')->log($error['severity_level'], '%type: @message in %function (line %line of %file).', $error);
67 $is_critical = !$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500;
69 error_log(sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine()));
76 * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
77 * The event to process.
79 public function onException(GetResponseForExceptionEvent $event) {
80 $exception = $event->getException();
84 // Treat any non-HTTP exception as if it were one, so we log it the same.
85 if ($exception instanceof HttpExceptionInterface) {
86 $possible_method = 'on' . $exception->getStatusCode();
87 if (method_exists($this, $possible_method)) {
88 $method = $possible_method;
92 $this->$method($event);
98 public static function getSubscribedEvents() {
99 $events[KernelEvents::EXCEPTION][] = ['onException', 50];