Gadelkareem
Gadelkareem

Reputation: 1087

Symfony 2 exceptions logging

I am planning to create custom exceptions for my application but I can not find a clean way to log the exceptions to monolog with a custom error level. I also wonder how Symfony logs those exceptions as I see some Exceptions are logged while others are not.

Upvotes: 1

Views: 5826

Answers (2)

Gadelkareem
Gadelkareem

Reputation: 1087

The key was fos_rest.exception_listener.class for my app as I use the fos_rest:

<?php
namespace AppBundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\EventListener\ExceptionListener as SymfonyExceptionListener;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;


class ExceptionListener extends SymfonyExceptionListener
{

    protected function logException(\Exception $exception, $message, $original = true)
    {

       //@TODO add some logic here


        $isCritical = !$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500;
        $context = ['exception' => $exception];
        if (null !== $this->logger) {
            if ($isCritical) {
                $this->logger->critical($message, $context);
            } else {
                $this->logger->error($message, $context);
            }
        } elseif (!$original || $isCritical) {
            error_log($message);
        }
    }


}

And add your class to your parameters

#app/config/parameters.yml
parameters:
    fos_rest.exception_listener.class: 'AppBundle\EventListener\ExceptionListener'

Upvotes: 4

Reformat Code
Reformat Code

Reputation: 307

Here is a clean example:

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/file.log', Logger::WARNING));

// add records to the log
$log->addWarning('Foo');
$log->addError('Bar');

You can add warnings or errors etc.

Upvotes: 0

Related Questions