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

Logging 如何在身份验证期间创建系统日志?,logging,symfony4,Logging,Symfony4,我在这里遵循指南并实施了基本身份验证系统: 但是,我想将系统日志添加到我的应用程序中。确切地说,我想: 能够插入在什么时间成功登录的记录 能够记录某人尝试登录但失败的时间 我知道我可以在SecurityController中放入日志,如下所示: public function login(AuthenticationUtils $authenticationUtils, Request $request, EntityManagerInterface $em): Response {

我在这里遵循指南并实施了基本身份验证系统:

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

  • 能够插入在什么时间成功登录的记录
  • 能够记录某人尝试登录但失败的时间
我知道我可以在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活动来完成。登录尝试失败/成功后触发这两个事件:
security.authentication.success
security.authentication.failure

我将为成功树立榜样,你也可以为失败树立榜样:

  • 将其添加到您的
    config/service.yml

    App\EventListener\SuccessLoginListener:
    tags:
        - { name: 'kernel.event_listener', event: 'security.authentication.success'}
    
  • 然后您可以创建侦听器并在其中执行日志记录过程

    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.
    }
    }
    

  • 要完全控制您的身份验证逻辑,通常的方法是实现一个。谢谢,它可以工作,但在注销操作期间以及我只需单击“登录”按钮时,它也会创建额外的日志。你知道如何单独处理吗?我很高兴看到这个解决了你的问题。您应该检查另一个Symfony安全身份验证事件。