phpsentrysymfony-console

Enabling Sentry on Symfony console program without the whole symfony being installed


I have this plain console program:

namespace MyApp\Console;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;

class MaConsole extends Command {
 protected function configure()
 {  
    $this->setDescription('Console\'s not console');
 }

  protected function execute(
        \Symfony\Component\Console\Input\InputInterface $input,
        \Symfony\Component\Console\Output\OutputInterface $output
  ) {
    $output->writeln('Doing Stuff');
  }
}

And I load it like that:

namespace MyApp;

use Symfony\Component\Console\Application as SymfonyApplication;
use MyApp\Console\MaConsole;

class Application extends SymfonyApplication
{
    public function __construct(
        string $name = 'staff',
        string $version = '0.0.1'
    ) {
        parent::__construct($name, $version);

        throw new \Exception('Test Sentry on Playground');
        $this->add(new MaConsole());
    }
}

And I want to log the exception thrown above in Sentry service. So I my entrypoint is:

use MyApp\Application;

require __DIR__ . '/vendor/autoload.php';

Sentry\init([
    'dsn' => getenv('SENTRY_DSN'),
    'environment' => getenv('ENVIRONMENT')
]);

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

But I fail to log the error into sentry, even thouhg I have set the correct enviromental variables.

The application does not load the Full Symfony framework, but instead it uses the console only components so I have no idea if I should use the Sentry Symfony Integration: https://docs.sentry.io/platforms/php/symfony/

The reason why is because I do not know how in my case to load the bundle, therefore I use the SDK.

Edit 1:

I also tried to catch the exception and manually log it but form some reason is not logged as well:

use MyApp\Application;

require __DIR__ . '/vendor/autoload.php';

try {
  Sentry\init([
    'dsn' => getenv('SENTRY_DSN'),
    'environment' => getenv('ENVIRONMENT')
  ]);
  throw new \Exception('Test Sentry on Playground');

  $application = (new Application())->run();
} catch(Exception $e) {
    Sentry\captureException($e);
}

Solution

  • You can use the dispatcher :

    use Symfony\Component\EventDispatcher\EventDispatcher;
    
    $dispatcher = new EventDispatcher();
    $dispatcher->addListener(ConsoleEvents::ERROR, function (ConsoleErrorEvent $event) use ($env) {
        Sentry\init([
            'dsn' => getenv('SENTRY_DSN'),
            'environment' => $env
        ]);
        Sentry\captureException($event->getError());
    });
    
    $kernel = new AppKernel($env, $debug);
    $application = new Application($kernel);
    $application->setDispatcher($dispatcher);
    $application->run($input);