gpt4 book ai didi

php - 在 symfony2 中记录 swiftmailer send() 事件

转载 作者:IT王子 更新时间:2023-10-29 00:21:27 25 4
gpt4 key购买 nike

我使用 swiftmailer 从我的 symfony2.2 项目发送邮件。有没有办法在全局范围内记录所有电子邮件信息并发送结果?

如果邮件程序 send() 方法触发某个事件就好了,但我看不到。

最佳答案

这个问题已经回答了,这个解决方案更适合 Symfony 4 结合 Monolog。它基于 umpirsky 他的答案。但没有自定义文件记录器的开销。

注意:日志会放在./var/logs/...

App\Util\MailLoggerUtil.php

<?php

namespace App\Util;

use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Swift_Events_SendEvent;
use Swift_Events_SendListener;

class MailerLoggerUtil implements Swift_Events_SendListener
{
protected $logger;

/**
* MailerLoggerUtil constructor.
*
* @param LoggerInterface $logger
*/
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}

/**
* @param Swift_Events_SendEvent $evt
*/
public function beforeSendPerformed(Swift_Events_SendEvent $evt)
: void
{
// ...
}

/**
* @param Swift_Events_SendEvent $evt
*/
public function sendPerformed(Swift_Events_SendEvent $evt)
: void
{
$level = $this->getLogLevel($evt);
$message = $evt->getMessage();

$this->logger->log(
$level,
$message->getSubject().' - '.$message->getId(),
[
'result' => $evt->getResult(),
'subject' => $message->getSubject(),
'to' => $message->getTo(),
'cc' => $message->getCc(),
'bcc' => $message->getBcc(),
]
);
}

/**
* @param Swift_Events_SendEvent $evt
*
* @return string
*/
private function getLogLevel(Swift_Events_SendEvent $evt)
: string
{
switch ($evt->getResult()) {
// Sending has yet to occur
case Swift_Events_SendEvent::RESULT_PENDING:
return LogLevel::DEBUG;

// Email is spooled, ready to be sent
case Swift_Events_SendEvent::RESULT_SPOOLED:
return LogLevel::DEBUG;

// Sending failed
default:
case Swift_Events_SendEvent::RESULT_FAILED:
return LogLevel::CRITICAL;

// Sending worked, but there were some failures
case Swift_Events_SendEvent::RESULT_TENTATIVE:
return LogLevel::ERROR;

// Sending was successful
case Swift_Events_SendEvent::RESULT_SUCCESS:
return LogLevel::INFO;
}
}
}

services.yaml

App\Util\MailLoggerUtil:
arguments: ["@logger"]
tags:
- { name: monolog.logger, channel: mailer }
- { name: "swiftmailer.default.plugin" }

如果您希望邮件程序日志在另一个 channel 中,请添加:

dev/monolog.yaml(可选)

monolog:
handlers:
mailer:
level: debug
type: stream
path: '%kernel.logs_dir%/mailer.%kernel.environment%.log'
channels: [mailer]

关于php - 在 symfony2 中记录 swiftmailer send() 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18033210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com