Created
June 20, 2023 18:06
-
-
Save ducho/b99139333d6ce79d4c49495a2959f6ad to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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