I'm using Monolog (https://github.com/Seldaek/monolog) in my PHP 8.1 project with no other framework (it's only a small project), it has a main class that does the bulk of the work and the main file. I want my program to write to the screen/a file plus e-mail the log.
I've initialised the logger:
use Monolog\Formatter\HtmlFormatter;
use Monolog\Handler\NativeMailerHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Level;
use Monolog\Logger;
$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());
I updated the class passing the logger instance, however I'm unsure if this is the correct way (thinking it will get a copy of the object, I thought about sending it by reference but I couldn't see others doing that), its outputs to the screen, but at the end of the script it sends no e-mail, the mailHandlier->send()
is protected so cannot be accessed by the main script.
$classAPI = new classAPI($logger);
Inside classAPI
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();
}
Any help would be much appreciated
You did not push your email handler. So, it is not taken into account. You may want to check out this Monolog lib to set up handlers, formatters, etc effortlessly with a single config file => https://github.com/theorchard/monolog-cascade. Additionally you can get the logger from anywhere in your code using a Registry so you don't have to pass the logger object around which is quite tidious.