use Psr\Log\LoggerInterface; use Psr\Log\AbstractLogger; use Psr\Log\LogLevel; class FatalLogger extends AbstractLogger implements LoggerInterface { public function log($level, $message, array $context = array()) { if ($level == LogLevel::EMERGENCY) { $this->logToFile($message); } } private function logToFile($message) { // Log the message to a file $file = '/path/to/file.log'; $handle = fopen($file, 'a'); fwrite($handle, $message . "\n"); fclose($handle); } } // Usage $logger = new FatalLogger(); try { // some code } catch (\Throwable $e) { $level = LogLevel::EMERGENCY; $message = $e->getMessage(); $logger->log($level, $message); }
use Monolog\Logger; use Monolog\Handler\StreamHandler; // Create a logger $logger = new Logger('fatal'); $logger->pushHandler(new StreamHandler('/path/to/file.log', Logger::EMERGENCY)); try { // some code } catch (\Throwable $e) { // Log the fatal error $logger->log(Logger::EMERGENCY, $e->getMessage(), ['exception' => $e]); }This code shows how to use the Monolog library to log fatal errors to a file. It creates a logger object, adds a handler to write to a file, and then logs the error with the severity level `EMERGENCY`. The error message and exception object are passed as context to the log function, so they can be included in the log file. In conclusion, both examples use different package libraries - the first example uses `PSR-3 Logger Interface` while the second example uses `Monolog`.