如何在Symfony中发送异常或错误的日志到电子邮件?

问题描述 投票:0回答:1

我的要求: Whenever an error occurs in application send that error logs to email.

我正试图将我们的应用程序中发生的任何例外error日志发送到电子邮件。下面是我试过的,但我没有收到电子邮件中的日志。

注意事项: 电子邮件发送功能工作正常,因为我已经在测试控制器中进行了测试。但是用这个Listener就不行了。

当我点击TestController Index Route时会发生什么?

当我访问 index 路由它抛出500内部服务器错误(因为我们故意抛出一个异常)。但是如果这个异常发生,它应该将日志发送到电子邮件。因为在ExceptionListener中,我已经编好了发送日志的电子邮件。但是它并没有发送日志(.ExceptionListener.php)。

ExceptionListener.php:

<?php

namespace App\EventListener;

use App\Service\EmailService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;

class ExceptionListener
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public function onKernelException(EmailService $emailService, ExceptionEvent $event)
    {
        // You get the exception object from the received event
        $exception = $event->getThrowable();
        $message = sprintf(
            'My Error says: %s with code: %s',
            $exception->getMessage(),
            $exception->getCode()
        );

        try {
            $emailService->sendLogToMail("[email protected]", $message);
        } catch (TransportExceptionInterface $e) {
            //
        }

    }
}

我已将监听者登记在 服务.yaml:

App\EventListener\ExceptionListener:
        tags:
            - { name: kernel.event_listener, event: kernel.exception }

TestController 我故意在其中产生一个异常。

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Exception;

class TestController extends AbstractController
{

    public function index() {

      throw new Exception("It's bad");

    }

}

我使用的是Symfony v4.4。

php symfony exception logging symfony4
1个回答
1
投票

编辑2:在构造函数中添加电子邮件服务,并坚持使用标准的onKernelException定义。

在symfony文档中有一篇非常好的文章来讨论这个问题。文档

如果你使用的是Monolog和SwiftMailer,这在几分钟内就可以完成。我觉得一切都解释得超好,但如果你遇到困难,请告诉我们。

EDIT:其实我注意到你没有使用Monolog。我建议使用它,这样你也有一个带有错误的日志文件。一旦完成,每当你发射 $this->logger->error('My error'); 将会发送一封带有错误和堆栈跟踪的电子邮件。这在生产初期非常方便。


1
投票

首先,你的监听器的服务定义中缺少了以下内容 method 属性。

- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

现在运行下面的命令,列出注册的事件监听器处理程序。kernel.exception 事件。

php app/console debug:event-dispatcher kernel.exception

如果您的监听器没有 显示检查你的服务配置。

如果它 是否 显示但仍未被调用,请检查 priority 的监听器。它的优先级可能比框架提供的默认监听器低,而且异常可能已经被另一个监听器处理,停止了事件的进一步传播。

如果是这种情况,请将 priority (优先级较高的被先调用)的监听器,让它提前被调用。

services:
  App\EventListener\ExceptionListener:
    tags:
      - { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 1000 } 
© www.soinside.com 2019 - 2024. All rights reserved.