This is my approach to use the logger service in console commands.
First I configure the channel and handler for my logger, it is configured on config.yml
My custom channel is named as con and the handler as conlog, but you can put names you want:
# app/config/config.yml
monolog:
channels: ['con']
handlers:
conlog:
type: rotating_file
max_files: 31
path: %kernel.logs_dir%/command.log
level: debug
channels: ['con']
I use a rotating_file type because my console command is executed all days by a scheduled task and
I need to do a daily tracking of the command but you can use the type you need. More info about handler types in docs
Now you can use the logger in your console command, the important thing here is to inject monolog service using the automatically registered logger service with the name of the channel, in my sample it is:
monolog.logger.con
More info about this in docs
// src/AcmeBundle/Command/YourCommand
class YourCommand extends ContainerAwareCommand
{
protected function execute(InputInterface $input, OutputInterface $output)
{
$logger = $this->getContainer()->get('monolog.logger.con');
$myMessage = 'The first message';
$output->writeln($myMessage);
$logger->info($myMessage);
}
}
And this is all, in this sample the log is saved in log directory with file names as: command-Y-m-d.log.
Finally it is important remarks that the con channel logger messages are added to dev.log too. If you want prevent it, it will be needed to configure channels option in main handler, on config_dev.yml, and prefix with ! our custom channel name:
# app/config/config_dev.yml
monolog:
handlers:
main:
type: stream
path: %kernel.logs_dir%/%kernel.environment%.log
level: debug
channels: ['!con']
executefunction by adding logging.>> mycommand.txt