Symfony2 and Doctrine: Print sql queries in a Command

For debugging purposes, it's sometimes usefull to print the queries executed by a Symfony2 Command. Here is my tiny piece of code to do it.

protected function execute(InputInterface $input, OutputInterface $output)
    {
        // your code here
 
        // printing sql queries
        $logger = $this->getContainer()->get('monolog.logger.doctrine');
 
        foreach ($logger->getLogs() as $log)
        {
            $output->writeln(sprintf('Query: %s', $log['message']));
        }
    }

Haut de page