Skip to content
Advertisement

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

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:

JavaScript

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:

JavaScript

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.

Advertisement

Answer

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

JavaScript

You can also use the PsrLogLoggerAwareInterface (which is as simple as use the PsrLogLoggerAwareTrait) and the logger will be injected automatically if available.

JavaScript

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement