src/Services/Monolog/ExtraProcessor.php line 50

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. // $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, ...
  27. $record['extra']['user'] = [
  28. 'id' => $this->user->getId(),
  29. 'email' => $this->user->getEmail(),
  30. 'roles' => $this->user->getRoles(),
  31. ];
  32. }
  33. if (null !== $this->postParams) {
  34. // Includes all posted parameter when the error occurred
  35. $record['extra']['postParams'] = $this->postParams;
  36. }
  37. return $record;
  38. }
  39. /**
  40. * @param RequestEvent $event
  41. */
  42. public function onKernelRequest(RequestEvent $event)
  43. {
  44. // Retain post parameters sent (serialized) in order to log them if needed
  45. $postParams = $event->getRequest()->request->all();
  46. if (false === empty($postParams)) {
  47. $this->postParams = serialize($postParams);
  48. }
  49. // Do not continue if user is not logged
  50. if (null === $token = $this->tokenStorage->getToken()) {
  51. return;
  52. }
  53. if (!is_object($user = $token->getUser())) {
  54. // e.g. anonymous authentication
  55. return;
  56. }
  57. // Retain the user entity in order to use it
  58. $this->user = $user;
  59. }
  60. }