I'd like to add the userId
and username
, provided by FOSUserBundle
, to my Logger (Monolog). I followed this tutorial to be able to log the IP, it's working.
My code below breaks, because $this->tokenStorage->getToken()
is NULL
, even if I'm logged in.
services.yml
monolog.processor.user:
class: AppBundle\Log\UserProcessor
arguments: [ "@request_stack", "@security.token_storage" ]
tags:
- { name: monolog.processor }
AppBundle/Log/UserProcessor.php
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use AppBundle\Entity\User;
class UserProcessor
{
private $requestStack;
private $tokenStorage;
public function __construct(RequestStack $requestStack, TokenStorageInterface $tokenStorage)
{
$this->requestStack = $requestStack;
$this->tokenStorage = $tokenStorage;
}
public function __invoke(array $record)
{
$username = '';
$userId = 0;
$user = $this->tokenStorage->getToken()->getUser();
// !!! ERROR !!!
// $this->tokenStorage->getToken() is NULL
if ($user instanceof User) {
$username = $user->getUsername();
$userId = $user->getId();
}
$record['extra']['user_id'] = $userId;
$record['extra']['username'] = $username;
return $record;
}
}
Any ideas? Thanks in advance!
The problem is that the processor is called to log something before security has been able to act and get the current user. Just check if token exists and if it doesn´t don't log user
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.