14

当我的 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 [] []
4

6 回答 6

8

我发现了一些有用的东西。kernel.exeption 事件上的Symfony2 内部文档提到可以在事件上设置响应,GetResponseForExceptionEvent 文档

一旦设置响应,此事件的传播就会停止。

我拼凑了一个似乎正在做我想做的事的听众:

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

}
于 2012-07-03T00:54:33.113 回答
6

这是一种代码更少的方法:)

1. 扩展 Symfonys ExceptionListner 类并覆盖 logging 方法:

<?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"
于 2013-03-18T19:09:09.283 回答
6

只需添加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以获取参考

于 2016-10-17T07:54:40.787 回答
1

基于 Tarjei 回答的 Symfony 5 解决方案:

创建一个覆盖 Symfony ErrorListener 的新 ErrorListener。

App\EventListener\ErrorListener.php

<?php
declare(strict_types=1);

namespace App\EventListener;

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

class ErrorListener extends BaseListener
{
    /**
     * Logs an exception.
     *
     * @param \Exception $exception The original \Exception instance
     * @param string     $message   The error message to log
     */
    protected function logException(\Throwable $exception, string $message): void
    {
        $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);
                }
            }
        }
    }
}

服务.yaml

services:
    App\EventListener\ErrorListener: '@exception_listener'

    exception_listener:
        autowire: false
        class: App\EventListener\ErrorListener
        arguments:
            $controller: '%kernel.error_controller%'
            $logger: '@logger'
            $debug: '%kernel.debug%'
于 2020-06-13T03:22:10.960 回答
1

您还可以使用错误级别活动策略(实际上 Symfony 的内置 404 错误排除是使用此完成的,所以我想这是一个正确的方法)。

配置.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

于 2016-03-02T10:01:16.630 回答
0

在 Symfony 3.3 中更喜欢这个而不是 exclude_404s 参数。

应用程序/配置/服务.yml

exception_listener:
    class: AppBundle\Listener\ExceptionListener
    arguments: ["@logger", "@templating"]
    tags:
        - { name: kernel.event_listener, event: kernel.exception}

src/AppBundle/Listener/ExceptionListener.php

<?php

namespace AppBundle\Listener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Bridge\Monolog\Logger;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Templating\EngineInterface;

class ExceptionListener
{
    private $logger;
    private $templateEngine;

    public function __construct(Logger $logger, EngineInterface $templateEngine)
    {
        $this->logger = $logger;
        $this->templateEngine = $templateEngine;
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();
        if ($exception instanceof NotFoundHttpException)
        {
            $this->logger->info($exception->getMessage());

            // default twig error app/config/Resources/TwigBundle/views/Exception/error.html.twig
            $response = $this->templateEngine->render('TwigBundle:Exception:error.html.twig');

            $event->setResponse(new Response($response));
        }
    }
}
于 2018-06-21T21:49:23.960 回答