|
14 | 14 | use Monolog\Handler\AbstractProcessingHandler; |
15 | 15 | use Monolog\Logger; |
16 | 16 | use Symfony\Bundle\MonologBundle\Formatter\ConsoleFormatter; |
| 17 | +use Symfony\Component\Console\ConsoleEvents; |
| 18 | +use Symfony\Component\Console\Event\ConsoleCommandEvent; |
| 19 | +use Symfony\Component\Console\Event\ConsoleTerminateEvent; |
17 | 20 | use Symfony\Component\Console\Output\ConsoleOutputInterface; |
18 | 21 | use Symfony\Component\Console\Output\OutputInterface; |
| 22 | +use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
19 | 23 |
|
20 | 24 | /** |
21 | 25 | * Writes to the console output depending on its verbosity setting. |
22 | 26 | * |
23 | | - * It is disabled by default and gets activated when setOutput is called. |
| 27 | + * It is disabled by default and gets activated as soon as a command is executed. |
| 28 | + * Instead of listening to the console events, setOutput can also be called manually. |
24 | 29 | * |
25 | 30 | * @author Tobias Schultze <http://tobion.de> |
26 | 31 | */ |
27 | | -class ConsoleHandler extends AbstractProcessingHandler |
| 32 | +class ConsoleHandler extends AbstractProcessingHandler implements EventSubscriberInterface |
28 | 33 | { |
29 | 34 | /** |
30 | 35 | * @var OutputInterface|null |
@@ -106,6 +111,38 @@ public function close() |
106 | 111 | parent::close(); |
107 | 112 | } |
108 | 113 |
|
| 114 | + /** |
| 115 | + * Before a command is executed, the handler gets activated and the console output |
| 116 | + * is set in order to know where to write the logs. |
| 117 | + * |
| 118 | + * @param ConsoleCommandEvent $event |
| 119 | + */ |
| 120 | + public function onCommand(ConsoleCommandEvent $event) |
| 121 | + { |
| 122 | + $this->setOutput($event->getOutput()); |
| 123 | + } |
| 124 | + |
| 125 | + /** |
| 126 | + * After a command has been executed, it disables the output. |
| 127 | + * |
| 128 | + * @param ConsoleTerminateEvent $event |
| 129 | + */ |
| 130 | + public function onTerminate(ConsoleTerminateEvent $event) |
| 131 | + { |
| 132 | + $this->close(); |
| 133 | + } |
| 134 | + |
| 135 | + /** |
| 136 | + * {@inheritdoc} |
| 137 | + */ |
| 138 | + public static function getSubscribedEvents() |
| 139 | + { |
| 140 | + return array( |
| 141 | + ConsoleEvents::COMMAND => 'onCommand', |
| 142 | + ConsoleEvents::TERMINATE => 'onTerminate' |
| 143 | + ); |
| 144 | + } |
| 145 | + |
109 | 146 | /** |
110 | 147 | * {@inheritdoc} |
111 | 148 | */ |
|
0 commit comments