monolog-bundle: Exclude 403 (4XX) Errors from the Log

Hello.

If I throw a Symfony\Component\Security\Core\Exception\AccessDeniedException or a Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException I do not want a log about this exception, because I thrown it.

For the security, The Symfony\Component\Security\Core\Exception\AccessDeniedException is converted to a Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException in the Symfony\Component\Security\Http\Firewall\ExceptionListener::handleAccessDeniedException.

I think we can extends the configuration to all kind of exception in the namespace Symfony\Component\HttpKernel\Exception\*, because If I throw an HttpKernel exception, it don’t want a log.

What do you think ?

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 28 (13 by maintainers)

Most upvoted comments

a simple solution is to add a custom activation strategy:

monolog:
    handlers:
        main:
            type:         fingers_crossed
            action_level: error
            handler:      nested
            activation_strategy: my.activation.strategy # service id

and then have a service like the following:

<?php

use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy;
use Symfony\Component\HttpKernel\Exception\HttpException;
use JMS\DiExtraBundle\Annotation as DI;

/**
 * Activation strategy for logs
 *
 * @DI\Service("my.activation.strategy")
 */
class LogActivationStrategy extends ErrorLevelActivationStrategy
{
    /**
     * LogActivationStrategy constructor.
     */
    public function __construct()
    {
        parent::__construct('error');
    }

    /**
     * @param array $record
     *
     * @return bool
     */
    public function isHandlerActivated(array $record)
    {
        $isActivated = parent::isHandlerActivated($record);
        if (
            $isActivated
            && isset($record['context']['exception'])
        ) {
            $exception = $record['context']['exception'];

            if ($exception instanceof HttpException) {
                // only log exceptions outside of 404 and 403
                return !in_array($exception->getStatusCode(), [403, 404]);
            }
        }

        return $isActivated;
    }
}

It seems that this only works thefingers crossed type. Doesn’t seem to work for a stream

Hi!

I have added excluded_http_codes: [403, 404] to all my logg-handlers, but I still receive alot of access-denied emails after ugprading from 4.0.8 to 4.1.0:

https://paste.gnome.org/panmtutis#line-37 https://i.imgur.com/s2X5mNb.png

Thanks fmonts! Would it be possible to backport this to 3.4 using a bundle?

Any news about this issue? I would like to be able to filter Monolog exceptions based on their HTTP status code or their exception code.

Is it possible?

Thanks.

@RichardBradley you can also decorate the service instead of replacing it, this should be somewhat more stable.