Skip to content

Instantly share code, notes, and snippets.

@ducho
Created June 20, 2023 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ducho/b99139333d6ce79d4c49495a2959f6ad to your computer and use it in GitHub Desktop.
Save ducho/b99139333d6ce79d4c49495a2959f6ad to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace App\Handler;
use Doctrine\ORM\EntityManagerInterface;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\LogRecord;
use Satur\DatabaseBundle\Entity\Log;
use Symfony\Bundle\SecurityBundle\Security;
class MonologDoctrineHandler extends AbstractProcessingHandler
{
private EntityManagerInterface $entityManager;
private Security $security;
public function __construct(EntityManagerInterface $entityManager, Security $security)
{
parent::__construct();
$this->entityManager = $entityManager;
$this->security = $security;
}
protected function write(LogRecord $record): void
{
if (!isset($record['context']['entity'])) {
return;
}
$entity = $record['context']['entity'];
unset($record['context']['entity']);
$record['context']['service'] = get_class($entity);
$logEntry = (new Log())->setMessage($record['message'])
->setLevel($record['level'])
->setLevelName($record['level_name'])
->setExtra($record['extra'])
->setUser($this->security->getUser())
->setContext($record['context']);
try {
$this->entityManager->persist($logEntry);
$this->entityManager->flush();
} catch (\Exception $exception) {
// TODO - ak sa nepodari zalogovat event treba vytvorit notifikaciu
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment