在具有到屏幕和电子邮件的输出的类中使用monlog



我正在使用Monolog(https://github.com/Seldaek/monolog)在我的PHP 8.1项目中,没有其他框架(这只是一个小项目(,它有一个主类来完成大部分工作和主文件。我希望我的程序写入屏幕/一个文件加上电子邮件日志。

我已经初始化了记录器:

use MonologFormatterHtmlFormatter;
use MonologHandlerNativeMailerHandler;
use MonologHandlerStreamHandler;
use MonologLevel;
use MonologLogger;
$logger = new Logger('getData');
$logger->pushHandler(new StreamHandler('php://stdout', Level::Debug));
// Email handling
$mailHandlier = new NativeMailerHandler($_ENV['MAILTO'], $serverName . " - " . implode(" ", $argv), $_ENV['MAILFROM'] ?? null, Level::Info, true, 80);
$mailHandlier->setFormatter(new HtmlFormatter());

我更新了传递记录器实例的类,但我不确定这是否是正确的方式(我认为它会获得对象的副本,我想过通过引用发送它,但我看不到其他人这样做(,它将输出到屏幕,但在脚本结束时,它不发送电子邮件,mailHandlier->send()受到保护,因此主脚本无法访问。

$classAPI = new classAPI($logger);

内部类API

public function __construct(Logger $logger)
{
// Inherit logging framework
$this->logger = $logger;
}

public function __destruct()
{
// Calculate runtime
$endTime = new DateTime();
$timeDiff = $endTime->diff($this->startTime, true);
$this->logger->info("API Completed: " . $endTime->format("D d M Y H:i") . ", Runtime: " . $timeDiff->format('%H:%I:%S') . " Complete");
$this->logger->close();
}

如有任何帮助,将不胜感激

您没有推送您的电子邮件处理程序。因此,它没有被考虑在内。您可能想要查看此Monolog库,以便使用单个配置文件轻松设置处理程序、格式化程序等=>https://github.com/theorchard/monolog-cascade.此外,您可以使用注册表从代码中的任何位置获取记录器,这样您就不必传递记录器对象,因为它非常整洁。

最新更新