在不安装整个 symfony 的情况下在 Symfony 控制台程序上启用 Sentry

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

我有这个简单的控制台程序:

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');
  }
}

然后我这样加载它:

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());
    }
}

并且我想在 Sentry 服务中记录上面抛出的异常。所以我的切入点是:

use MyApp\Application;

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

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

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

但我无法将错误记录到哨兵中,即使我已经设置了正确的环境变量。

应用程序不加载完整的 Symfony 框架,而是使用仅控制台组件,所以我不知道是否应该使用 Sentry Symfony 集成:https://docs.sentry.io/platforms/php/symfony/

原因是因为我不知道如何加载包,所以我使用SDK。

编辑 1:

我也尝试捕获异常并手动记录它,但出于某种原因也没有记录:

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);
}

您可以使用调度程序:

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);