In this cookbook article, we can see how to use a custom channel in a service. But how can I use a custom login channel in a command ?
I created a symfony2 command to perform something. I would like to use monolog to log things done by my command.
Actually, I want to write log for my command in another file than the logs of the application.
Any custom command that extends ContainerAwareCommand, has access to Symfony's service container. You can define a service that logs in a custom channel in your config.  
<services>
    <service id="console.logger" parent="monolog.logger_prototype">
        <argument index="0">mychannel</argument>
    </service>
</services>
You can access your service from the command the following way
$logger = $this->getContainer()->get('console.logger');
This logger will log with channel as "mychannel".
FYI The default logger service logs to channel "app". This can be seen in the file
Symfony/Bundle/MonologBundle/Resources/config/monolog.xml. This is also the place where the default logger service is defined.
<services>
    <service id="monolog.logger" parent="monolog.logger_prototype" public="false">
        <argument index="0">app</argument>
    </service>
    <service id="logger" alias="monolog.logger" />
    <service id="monolog.logger_prototype" class="%monolog.logger.class%" abstract="true">
        <argument /><!-- Channel -->
    </service>
</services>
                        A similar question were asked and answered here:
How to write logs from one service into separate file?
Thanks
Try this, use the library directly
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// ...
// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path of log file', Logger::WARNING));
//add the erros to log file
try {
    //do something
} catch(Exception $e) {
    $log->addError($e->getMessage());
}
Maybe this can resolve your problem, add this into your command file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With