如何在身份验证期间创建系统日志?

How do I create system logs during authentication?

我按照此处的指南实施了基本身份验证系统: https://symfony.com/doc/current/security.html

但是,我想将系统日志添加到我的应用程序中。准确地说,我想要:

我知道我可以将日志放入我的 SecurityController,如下所示:

public function login(AuthenticationUtils $authenticationUtils, Request $request, EntityManagerInterface $em): Response
{
    // if ($this->getUser()) {
    //     return $this->redirectToRoute('target_path');
    // }

    $log = new Logs();
    $em->persist($log);

    $log->setAction('auth')
        ->setDate(new DateTime())
        ->setIp($request->getClientIp());

    $em->flush();

    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();
    // last username entered by the user
    $lastUsername = $authenticationUtils->getLastUsername();

    return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}

但它只向我提供了有人在登录页面上的信息。我要修改或添加什么以获得其他信息?

我想这会解决你的问题。

你应该通过 Symfony 事件来完成。 failed/succeed 次登录尝试后触发的这两个事件:security.authentication.successsecurity.authentication.failure .

成功我做一个例子,失败你可以借鉴:

  1. 将此添加到您的 config/service.yml

    App\EventListener\SuccessLoginListener:
    tags:
        - { name: 'kernel.event_listener', event: 'security.authentication.success'}
    
  2. 然后你可以创建监听器并在其中记录进程

    namespace App\EventListener;
    
    use Doctrine\ORM\EntityManagerInterface;
    use Symfony\Component\Security\Http\Event\AuthenticationSuccessEvent;
    
    class SuccessLoginListener
    {
    private $em;
    
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }
    
    public function onSecurityAuthenticationSuccess(AuthenticationSuccessEvent $event)
    {
    // TODO: Create your log entity at here.
    }
    }