<?php
namespace App\Services\Monolog;
use App\Entity\User;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class ExtraProcessor
{
/**
* @var string
*/
private $postParams = NULL;
/**
* @var TokenStorageInterface
*/
private TokenStorageInterface $tokenStorage;
/** @var User $user */
private $user = NULL;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
// Called when an error occurred and a log (record) is creating
public function __invoke(array $record): array
{
if(NULL !== $this->user)
{
// $this->user is your user's entity. Extract all pertinent data you would need. In this case, getUserDetails method create a summary including alias, name, role, ...
$record['extra']['user'] = [
'id' => $this->user->getId(),
'email' => $this->user->getEmail(),
'roles' => $this->user->getRoles(),
];
}
if(NULL !== $this->postParams)
{
// Includes all posted parameter when the error occurred
$record['extra']['postParams'] = $this->postParams;
}
return $record;
}
/**
* @param RequestEvent $event
*/
public function onKernelRequest(RequestEvent $event)
{
// Retain post parameters sent (serialized) in order to log them if needed
$postParams = $event->getRequest()->request->all();
if(FALSE === empty($postParams))
{
$this->postParams = serialize($postParams);
}
// Do not continue if user is not logged
if(NULL === $token = $this->tokenStorage->getToken())
{
return;
}
if(!is_object($user = $token->getUser()))
{
// e.g. anonymous authentication
return;
}
// Retain the user entity in order to use it
$this->user = $user;
}
}