How do I reduce the severity of NotFoundHttpException?

You can also use error level activity strategy (actually Symfony's in-built 404 errors excluding is done using this, so I guess this is a proper way to do it).

config.yml

monolog:
    handlers:
        main:
            type: fingers_crossed
            handler: loggly
            activation_strategy: 'mybundle.monolog.fingers_crossed.activation_strategy'
        loggly:
            type: loggly
            token: %loggly_token%
            level: error
            tag: %loggly_tag%

services.yml (note that action level is set here, not in config.yml)

services:
    mybundle.monolog.fingers_crossed.activation_strategy:
        class: MyBundle\Handler\FingersCrossed\ErrorLevelActivationStrategy
        arguments:
            - '@request_stack'
            - 'error'

ErrorLevelActivationStrategy.php

<?php
namespace MyBundle\Handler\FingersCrossed;

use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy as BaseErrorLevelActivationStrategy;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Activation strategy that ignores client errors (4xx)
 */
class ErrorLevelActivationStrategy extends BaseErrorLevelActivationStrategy
{
    protected $requestStack;
    public function __construct(RequestStack $requestStack, $actionLevel)
    {
        parent::__construct($actionLevel);
        $this->requestStack = $requestStack;
    }
    /**
     * {@inheritdoc}
     */
    public function isHandlerActivated(array $record)
    {
        $isActivated = parent::isHandlerActivated($record);
        if (
            $isActivated
            && isset($record['context']['exception'])
            && $record['context']['exception'] instanceof HttpException
            && $record['context']['exception']->getStatusCode() >= 400
            && $record['context']['exception']->getStatusCode() <= 499
            && ($request = $this->requestStack->getMasterRequest())
        ) {
            $isActivated = false;
        }
        return $isActivated;
    }
}

https://gist.github.com/sobstel/d791d0347ee1f4e47b6e


Just add excluded_404s to your configuration:

monolog:
    handlers:
        main:
            type:         fingers_crossed
            action_level: error
            handler:      nested
            excluded_404s:
                - ^/
        nested:
            type:  stream
            path:  "%kernel.logs_dir%/%kernel.environment%.log"
            level: debug

See http://symfony.com/doc/current/logging/monolog_regex_based_excludes.html for a reference


I found something that works. The Symfony2 internals doc on the kernel.exeption event mention that a response can be set on the event, and the GetResponseForExceptionEvent docs say

The propagation of this event is stopped as soon as a response is set.

I cobbled together a listener that appears to do just what I want:

<?php

namespace Acme\DemoBundle\Listener;

use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

class ExceptionLoggingListener {
  private $logger;

  public function __construct(LoggerInterface $logger) {
    $this->logger = $logger;
  }

  public function onKernelException(GetResponseForExceptionEvent $event) {
    if(!$event) {
      $this->logger->err("Unknown kernel.exception in ".__CLASS__);
      return;
    }
    $notFoundException = '\Symfony\Component\HttpKernel\Exception\NotFoundHttpException';

    $e = $event->getException();
    $type = get_class($e);
    if ($e instanceof $notFoundException) {
      $this->logger->info($e->getMessage());
      $response = new Response(Response::$statusTexts[404], 404);
      $event->setResponse($response);
      return;
    }

    $accessDeniedException = '\Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException';
    if ($e instanceof $accessDeniedException) {
      $this->logger->info($e->getMessage());
      $response = new Response(Response::$statusTexts[403], 403);
      $event->setResponse($response);
      return;
    }
    $this->logger->err("kernel.exception of type $type. Message: '".$e->getMessage()."'\nFile: ".$e->getFile().", line ".$e->getLine()."\nTrace: ".$e->getTraceAsString());
  }

}

Here's a way with less code :)

1. Extend Symfonys ExceptionListner class and override the logging method:

<?php

use Symfony\Component\HttpKernel\EventListener\ExceptionListener as BaseListener;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;


class ExceptionListener extends BaseListener
{

    /**
     * Logs an exception.
     *
     * @param \Exception $exception The original \Exception instance
     * @param string     $message   The error message to log
     * @param Boolean    $original  False when the handling of the exception thrown another exception
     */
    protected function logException(\Exception $exception, $message, $original = true)
    {
        $isCritical = !$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500;

        if (null !== $this->logger) {
            if ($isCritical) {
                $this->logger->critical($message);
            } else {

                if ($exception instanceof NotFoundHttpException) {
                    $this->logger->info($message);
                } else {
                    $this->logger->error($message);
                }
            }
        } elseif (!$original || $isCritical) {
            error_log($message);
        }
    }
}

2. Configure the twig.exception_listener.class parameter:

parameters:
    twig.exception_listener.class: "MyBundle\EventListener\ExceptionListener"

Tags:

Symfony