src/Services/Monolog/ExtraProcessor.php line 52

Open in your IDE?
  1. <?php
  2. namespace App\Services\Monolog;
  3. use App\Entity\User;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  6. class ExtraProcessor
  7. {
  8. /**
  9. * @var string
  10. */
  11. private $postParams = NULL;
  12. /**
  13. * @var TokenStorageInterface
  14. */
  15. private TokenStorageInterface $tokenStorage;
  16. /** @var User $user */
  17. private $user = NULL;
  18. public function __construct(TokenStorageInterface $tokenStorage)
  19. {
  20. $this->tokenStorage = $tokenStorage;
  21. }
  22. // Called when an error occurred and a log (record) is creating
  23. public function __invoke(array $record): array
  24. {
  25. if(NULL !== $this->user)
  26. {
  27. // $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, ...
  28. $record['extra']['user'] = [
  29. 'id' => $this->user->getId(),
  30. 'email' => $this->user->getEmail(),
  31. 'roles' => $this->user->getRoles(),
  32. ];
  33. }
  34. if(NULL !== $this->postParams)
  35. {
  36. // Includes all posted parameter when the error occurred
  37. $record['extra']['postParams'] = $this->postParams;
  38. }
  39. return $record;
  40. }
  41. /**
  42. * @param RequestEvent $event
  43. */
  44. public function onKernelRequest(RequestEvent $event)
  45. {
  46. // Retain post parameters sent (serialized) in order to log them if needed
  47. $postParams = $event->getRequest()->request->all();
  48. if(FALSE === empty($postParams))
  49. {
  50. $this->postParams = serialize($postParams);
  51. }
  52. // Do not continue if user is not logged
  53. if(NULL === $token = $this->tokenStorage->getToken())
  54. {
  55. return;
  56. }
  57. if(!is_object($user = $token->getUser()))
  58. {
  59. // e.g. anonymous authentication
  60. return;
  61. }
  62. // Retain the user entity in order to use it
  63. $this->user = $user;
  64. }
  65. }