PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, January 10, 2022

[FIXED] How to use the logger in a console command on Symfony 4?

 January 10, 2022     dependency-injection, php, symfony, symfony4     No comments   

Issue

I've recently gone from using Symfony 2.7 to 4.2.

Previously in my commands in order to log to a file I used something like:

$logger = $this->getContainer()->get('logger');
$logger->error('put this in log');

This functionality appears to have changed. I can log from a controller following https://symfony.com/doc/current/logging.html

I can output to the console using:

$logger = new ConsoleLogger($output);
$logger->log('error','Put this in the log file');

But as much as I stare at the information on the symfony website I just can't figure out how to log to a file using symfony 4.2 from a command.


Solution

You need to inject the logger into your command, similarly as it is shown for the controller example.


class ExampleCommand extends Command {

    protected static $defaultName = 'do:something:awesome';
    /**
     * @var \Psr\Log\LoggerInterface
     */
    private $logger;

    public function __construct(  LoggerInterface $logger  ) {

        $this->$logger = $logger;

        parent::__construct(  );
    }

    public function execute( InputInterface $input, OutputInterface $output ) {
        $io = new SymfonyStyle( $input, $output );
        $this->logger->info('Logging like a boss at ' . __FILE__ . ':' . __LINE__);

       // the rest of your command
   }

You can also use the Psr\Log\LoggerAwareInterface (which is as simple as use the Psr\Log\LoggerAwareTrait) and the logger will be injected automatically if available.

class FooBar extends Command implements LoggerAwareInterface
{

    use LoggerAwareTrait;

// rest of the class implementation

}

With this you do not even need to use constructor injection, since Symfony will automatically call setLogger() on your command to inject the logger for you.

Your command will use the same logger configuration than the rest of your project, and you'll be logging to files in no time.



Answered By - yivi
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing