Подтвердить что ты не робот

Как уменьшить степень NotFoundHttpException?

Я хочу получать предупреждения, когда в моем приложении Symfony2 появляются плохие вещи. Сейчас я просто ищу ERROR в журналах. К сожалению, "HTTP 404 - файл не найден" (NotFoundHttpException) регистрируется как ошибка, также как и "HTTP 403 - запрещено" (AccessDeniedHttpException).

Это не гарантирует ошибку; в лучшем случае это должны быть предупреждения. Как я могу сделать этот журнал на менее строгом уровне?

Пример ошибки:

[2012-07-02 16:58:21] request.ERROR: Symfony\Component\HttpKernel\Exception\NotFoundHttpException: No route found for "GET /foo" (uncaught exception) at /home/user/Symfony2_v2.0.12/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/EventListener/RouterListener.php line 83 [] []
4b9b3361

Ответ 1

Я нашел что-то, что работает. Внутренний документ Symfony2 в событии kernel.exeption упоминает, что ответ может быть задан для события, а GetResponseForExceptionEvent docs скажем

Распространение этого события прекращается, как только ответа.

Я собрал слушателя, который, кажется, делает именно то, что я хочу:

<?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());
  }

}

Ответ 2

Вот путь с меньшим кодом:)

1. Расширьте класс Symfonys ExceptionListner и переопределите метод ведения журнала:

<?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. Настройте параметр twig.exception_listener.class:

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

Ответ 3

Просто добавьте excluded_404s к вашей конфигурации:

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

См. http://symfony.com/doc/current/logging/monolog_regex_based_excludes.html для ссылки

Ответ 4

Вы также можете использовать стратегию активности уровня ошибок (на самом деле это исключение из встроенных 404 ошибок Symfony производится, поэтому я думаю, что это правильный способ сделать это).

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 (обратите внимание, что здесь установлен уровень действия, а не в 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