Skip to content

Instantly share code, notes, and snippets.

@tobalsan
Created November 29, 2017 09:51
Show Gist options
  • Save tobalsan/999bef05a4ce544e410d18f72b0d84f7 to your computer and use it in GitHub Desktop.
Save tobalsan/999bef05a4ce544e410d18f72b0d84f7 to your computer and use it in GitHub Desktop.
Exclude 404 (NotFoundHttpException) from Symfony logs

Add a custom activation strategy:

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

Then have a service like the following:

<?php

namespace AppBundle\Service;

use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy;
use Symfony\Component\HttpKernel\Exception\HttpException;

/**
 * Activation strategy for logs
 */
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;
    }
}

Finally, register your service:

my.activation.strategy:
        class: AppBundle\Service\LogActivationStrategy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment