im have problem in monolog doctrine logging (in symfony 5):
framework.yaml:
monolog:
channels: [doctrine_channel]
handlers:
main:
channels: ["!event", "!doctrine_channel"]
doctrine:
type: service
channels: [doctrine_channel]
id: app.logger.doctrine_handler
services.yaml:
app.logger.doctrine_handler:
class: App\Util\DoctrineHandler
arguments:
- "@doctrine.orm.entity_manager"
src/Utils/DoctrineHandler.php:
<?
namespace App\Util;
use App\Entity\Logs;
use Doctrine\ORM\EntityManagerInterface;
use Monolog\Handler\AbstractProcessingHandler;
class DoctrineHandler extends AbstractProcessingHandler
{
private $initialized;
private $entityManager;
private $channel = 'doctrine_channel';
public function __construct(EntityManagerInterface $entityManager)
{
parent::__construct();
$this->entityManager = $entityManager;
}
protected function write(array $record): void
{
if (!$this->initialized) {
$this->initialize();
}
if ($this->channel != $record['channel']) {
return;
}
$log = new Logs();
//$log->setMessage($record['message']);
//$log->setLevel($record['level_name']);
$log->setMessage($record['message']);
$log->setLevel($record['level']);
$log->setLevelName($record['level_name']);
$log->setExtra($record['extra']);
$log->setContext($record['context']);
$this->entityManager->persist($log);
$this->entityManager->flush();
}
private function initialize()
{
$this->initialized = true;
}
}
Now in the sample controller file: in TestController.php
// in use inject LoggerInterface $logger
$this->logger = $logger;
$this->logger->info('test');
This is not logging to mysql database what is problem ? Thank you in advance for all the hints...
You need to to use bindings. Try this guide https://nehalist.io/logging-events-to-database-in-symfony/ And this https://symfony.com/blog/new-in-symfony-4-2-autowiring-by-type-and-name