Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom monolog logging channel in symfony2 command

Tags:

php

symfony

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.

like image 945
Reuven Avatar asked Oct 10 '11 15:10

Reuven


3 Answers

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>
like image 126
Venkat Kotra Avatar answered Nov 13 '22 06:11

Venkat Kotra


A similar question were asked and answered here:

How to write logs from one service into separate file?

Thanks

like image 26
Reuven Avatar answered Nov 13 '22 05:11

Reuven


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.

like image 4
Sandeep Gupta Avatar answered Nov 13 '22 07:11

Sandeep Gupta