如何使用Symfony2中的Monolog记录一行

时间:2015-06-05 10:46:33

标签: symfony phpunit monolog

我在Symfony2中使用Monolog,使用默认的MonologBu​​ndle。我试图在我的测试中断言,记录了一行。我已在config_test.yml

中对此进行了配置
monolog:
    handlers:
        main:
            type:   test
            level:  debug

如何在我的测试中获取Monolog的TestHandler结果(继承自Symfony2的WebTestCase)?

2 个答案:

答案 0 :(得分:5)

作为解决方案:

monolog服务和搜索测试处理程序中获取所有处理程序。

foreach ($this->container->get('monolog')->getHandlers() as $handler) {
  if ($handler instanceof TestHandler) {
    $testHandler = $handler;
    break;
  }
}

if (!$testHandler) {
  throw new \RuntimeException('Oops, not exist "test" handler in monolog.');
}

$this->assertFalse($testHandler->hasCritical()); // Or another assertions

答案 1 :(得分:0)

在命令类中,您只需使用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...
    }

在测试中,使用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());
    }
}

请注意array('verbosity' => OutputInterface::VERBOSITY_DEBUG)

通过这种方式,您可以获取所有日志(在这种情况下为INFO,使用$logger->info('Starting <info>acme:your:command</info>');设置):

[2015-08-13 23:39:22] app.INFO: Starting acme:your:command: 

现在,您可以使用$this->assertRegExp()检查特定行是否已记录。

您还可以使用

转换string中的array
explode('\n', $commandTester->getDisplay())

此解决方案为found here,并在Monolog here的文档中进行了解释。

有关Monolog and Symfony (Symfony Docu)的更多信息。

有关Monolog Handlers (Monolog Docu)的更多信息。