Nella classe di comando, è necessario impostare semplicemente il gestore con pushHandler()
:
namespace AppBundle\Command;
use Symfony\Bridge\Monolog\Handler\ConsoleHandler;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class YourCommand extends ContainerAwareCommand
{
// ...
protected function execute(InputInterface $input, OutputInterface $output)
{
$logger = $this->getContainer()->get('logger');
// PUSH THE OutputInterface OBJECT INTO MONOLOG
$logger->pushHandler(new ConsoleHandler($output));
// Your command logic here...
}
nel test, utilizzando CommandTester
:
namespace AppBundle\Tests\Command;
use AppBundle\Command\YourCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Tester\CommandTester;
class YourCommandTest extends KernelTestCase
{
public function testExecute()
{
$kernel = $this->createKernel();
$kernel->boot();
// mock the Kernel or create one depending on your needs
$application = new Application($kernel);
$application->add(new YourCommand());
$command = $application->find('acme:your:command');
$commandTester = new CommandTester($command);
$commandTester->execute(
array('command' => $command->getName()),
/**
* Here set the verbosity
*/
array('verbosity' => OutputInterface::VERBOSITY_DEBUG)
);
// die(print_r($commandTester->getDisplay()));
$this->assertRegExp('/.../', $commandTester->getDisplay());
}
}
mantenere l'attenzione al array('verbosity' => OutputInterface::VERBOSITY_DEBUG)
.
In questo modo sarete possibile ottenere tutti i registri (un'INFO in questo caso, insieme con $logger->info('Starting <info>acme:your:command</info>');
):
[2015-08-13 23:39:22] app.INFO: Starting acme:your:command:
Ora è possibile utilizzare $this->assertRegExp()
per verificare se una particolare linea viene registrato o meno.
Si può anche trasformare il string
in un array
con
explode('\n', $commandTester->getDisplay())
Questa soluzione erano found here ed è spiegato nella documentazione di Monolog here.
Ulteriori informazioni su Monolog and Symfony (Symfony Docu).
Maggiori informazioni su Monolog Handlers (Monolog Docu).
Non stavo cercando di affermare le righe di registro in un comando. Una soluzione più generica e generale sarebbe apprezzata. – hvtilborg
Penso di non capire cosa vorresti raggiungere ... Puoi aggiornare la tua domanda con qualche altro dettaglio? Pubblica il codice del test, in modo che possiamo vedere come lo hai implementato e darti una soluzione. – Aerendir