I’m no Symfony expert, I write what I find as I find it. Nothing in the documentation really covers this subject, so I am not sure what the correct way is of if there even is one.
There are a few ways I have found to get a user id. None of the classes you can inject such as UserInterface, SessionInterface, TokenInterface, Security etc. contain an actual getUserId() method.
You can get a user object from the Security class, as seen in the documentation here. To do so you type hint aka Dependency Inject your service constructor with Security but not just any Security will do there is also one by Sensio labs and another. You want this Security
Then your ide wont show it or will warn something about a polymorphic call blah blah, but apparently there is a getId() method of the user returned from Security and you can get a user id like this.
/** @var User $user */
$user = $this->security->getUser()->getId();
$userId = $user->getId();
This method may return null if the user is not logged in so you need to check for that. The @var syntax tells the IDE what is going on so it knows there is a getId() method, you will also need to import that class. The User object it refers to is your App/Entity/User class.
Forgive me if anything is wrong.
Link to a Symfony cast with a little more info but not much.