Symfony 2 Logging exceptions in console

Sawered picture Sawered · Feb 16, 2012 · Viewed 11.6k times · Source

Why errors from console tasks are not logged. For example Exception on php warning:

[ErrorException]
Notice: Undefined offset: 1 in /var/www/project/vendor/doctrine/lib/Doctrine/ORM/Query.php line 298

I see what printed in stdout, but nothing logged to logs. (I use console commands in cron). In web these exceptions logged with backtrace, which in this situation is more informational than just this exception.

As a solution: I enclose all process function in try..catch block and log the backtrace manually.

Is anyone know how to enable or configure logging in console tasks. I think it must be somewhere.

Answer

Martin picture Martin · Feb 16, 2012

As I followed the code, there's actually no such an option to enable logging for commands. In app/console is this code:

use Symfony\Bundle\FrameworkBundle\Console\Application;

...

$application = new Application($kernel);
$application->run();

It calls Symfony\Component\Console\Application::run() in which there's try/catch block. On exception method renderException() is called, but no logging happens anywhere.

Also note that app/console always by default exits with error code on exception.

You can create you own Application class extending Symfony\Bundle\FrameworkBundle\Console\Application and modify app/console to use it. Than you can override run() method and add errors logging.

Or you can modify just app/console and handle erros like this:

// $application->run();
$application->setCatchExceptions(false);
try {
    $output = new Symfony\Component\Console\Output\ConsoleOutput();
    $application->run(null, $output);
} catch (Exception $e) {
    ... error logging ...

    $application->renderException($e, $output);

    $statusCode = $e->getCode();
    $statusCode = is_numeric($statusCode) && $statusCode ? $statusCode : 1;
    exit($statusCode);
}