logging - Getting a Logger in Symfony WheNot in a Controller -
i'm working on entityrepository class, , need dump data log file. can't use dump() because isn't going build page; it's going return json. eventually.
normally, in controller, i'd use:
$logger = $this->getlogger();
but i'm not in controller.
thx help.
update: forensic logging. i'm using debugging purposes. it'll removed afterwards.
i looked bit. first hunch "well, if define entityrepositories services, make easy because inject logger"
but how inject logger repositories doctrine creating? turns out can specify own repository factory
i'm going assume needs implement doctrine\orm\repository\repositoryfactory
interface, you'll want subclass doctrine\orm\repository\defaultrepositoryfactory
.
you need create own, base repository class can hold logger. let's start there
src/appbundle/doctrine/entityrepository.php
<?php namespace appbundle\doctrine; use doctrine\orm\entityrepository; use psr\log\loggerinterface; class loggerawareentityrepository extends entityrepository { protected $logger; public function setlogger(loggerinterface $logger) { $this->logger = $logger; } }
now, factory
src/appbundle/doctrine/loggerawarerepositoryfactory.php
<?php namespace appbundle\doctrine; use doctrine\orm\repository\defaultrepositoryfactory; use doctrine\orm\entitymanagerinterface; use psr\log\loggerinterface; use appbundle\doctrine\loggerawareentityrepository; class loggerawarerepositoryfactory extends defaultrepositoryfactory { protected $logger; public function __construct(loggerinterface $logger) { $this->logger = $logger; } protected function createrepository(entitymanagerinterface $entitymanager, $entityname) { $repository = parent::createrepository($entitymanager, $entityname); if ($repository instanceof loggerawareentityrepository) { $repository->setlogger($this->logger); } return $repository; } }
now confguration glue make work
app/config/services.yml
services: logger_aware_repository_factory: class: appbundle\doctrine\loggerawarerepositoryfactory arguments: ['@logger']
app/config/config.yml
doctrine: orm: entity_managers: default: repository_factory: "@logger_aware_repository_factory"
lastly, actual implementation
src/appbundle/entity/somecustomrepository.php
<?php namespace appbundle\entity; use appbundle\doctrine\loggerawareentityrepository; class somecustomrepository extends loggerawareentityrepository { public function findsomethingcustom() { // log $this->logger->log('message'); } }
full disclosure: untested code - there might bugs!
Comments
Post a Comment