Log PHP fatal errors in Symfony2 using Monolog

fdellutri picture fdellutri · Mar 12, 2014 · Viewed 7.4k times · Source

I need a way to capture PHP fatal errors (but also notices and warnings) and logging them by using Monolog.

I found that Monolog 1.6+ has the ErrorHandler::register() method, but I can't figure out how to use it in a Symfony2 (production) application, and how properly configure it in config.yml.

Answer

fdellutri picture fdellutri · Mar 13, 2014

Thanks to @jenechka, who pointed me to the right direction, I think I found a solution:

services.yml:

    vir.exception.listener:
    class: %vir.exception.listener.class%
    arguments: ["@logger"]
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

Error Handler:

<?php

namespace Mitecube\VoglioilruoloBundle\Listener;

use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Psr\Log\LoggerInterface;

class VoglioilruoloErrorHandler extends ErrorHandler {

    private $logger;
    private $prevErrorHandler;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
        $this->prevErrorHandler = set_error_handler(array($this, 'handle'));
        register_shutdown_function(array($this, 'handleFatal'));
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
    }

    public function handle($level, $message, $file = 'unknown', $line = 0, $context = array())
    {
        $this->logger->error($level . ": " . $message . " - in file " . $file . " - at line " . $line);
        return parent::handle($level, $message, $file, $line, $context);
    }

} 

In this way I able to log each error to monolog. I don't think this solution can be considered a "best practice", so I'm still looking for a better solution.