In Symfony, it’s pretty easy to log messages in a file. You have to use the Monolog Bundle and then follow the instructions in:
https://symfony.com/doc/current/logging.html
But when you want to log in a separate document, it can be quite a hustle. An easy method which I found out is the following:
Define two new services (in any services.yml ):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
services: ... # additional logging services # my_new_logger: class: Symfony\Bridge\Monolog\Logger arguments: [new_logger] calls: - [pushHandler, ['@my_new_logger_handler']] my_new_logger_handler: class: Monolog\Handler\StreamHandler # 200 = INFO, see Monolog::Logger for the values of log levels arguments: ["%kernel.logs_dir%/%kernel.environment%.my_new_logger.log", 200] ... |
In the arguments of the service my_new_logger_handler you specify the path of the new file in which you want to log.
Then, using Dependency Injection, it’s pretty easy to include that new service and log info messages:
service.yml:
1 2 3 4 5 6 7 8 |
services: ... my_arbitrary_service: class: MyApp\MyBundle\Directory\MyService arguments: ['@my_new_logger'] ... |
MyService.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
use Symfony\Bridge\Monolog\Logger; class MyService { private $myLogger; public function __construct( Logger $myLogger ) { $this->myLogger = $myLogger; } public function testFunction() { $this->myLogger->info('Log test message'); } } |