Rumah >pembangunan bahagian belakang >tutorial php >Antara Muka PSR-Logger dalam PHP
Ahnii!
Baru-baru ini, saya telah membantu pasukan berhijrah daripada Monolog kepada penyelesaian pengelogan tersuai. Pengelogan mereka tidak diseragamkan, memerlukan perubahan kod merentas banyak fail. Ini menyerlahkan nilai PSR-3, penyelesaian yang saya akan tunjukkan di sini.
PSR-3 bertindak sebagai kontrak pembalakan dalam PHP. Sama seperti cara reka bentuk kereta standard memastikan kemudahan operasi merentas model yang berbeza, PSR-3 menyediakan gelagat perpustakaan pembalakan yang konsisten.
Kontrak ini mentakrifkan antara muka:
<code class="language-php"><?php namespace Psr\Log; interface LoggerInterface { public function emergency($message, array $context = array()); public function alert($message, array $context = array()); public function critical($message, array $context = array()); public function error($message, array $context = array()); public function warning($message, array $context = array()); public function notice($message, array $context = array()); public function info($message, array $context = array()); public function debug($message, array $context = array()); public function log($level, $message, array $context = array()); } ?></code>
Tahap ini mewakili skala keterukan:
Mari kita buat penulisan logger pada fail dan hantar ralat kritikal ke Slack:
<code class="language-php"><?php namespace App\Logging; use Psr\Log\AbstractLogger; use Psr\Log\LogLevel; class SmartLogger extends AbstractLogger { private $logFile; private $slackWebhook; public function __construct(string $logFile, string $slackWebhook) { $this->logFile = $logFile; $this->slackWebhook = $slackWebhook; } public function log($level, $message, array $context = array()) { $timestamp = date('Y-m-d H:i:s'); $message = $this->interpolate($message, $context); $logLine = "[$timestamp] [$level] $message" . PHP_EOL; file_put_contents($this->logFile, $logLine, FILE_APPEND); if (in_array($level, [LogLevel::CRITICAL, LogLevel::EMERGENCY])) { $this->notifySlack($level, $message); } } private function notifySlack($level, $message) { $emoji = $level === LogLevel::EMERGENCY ? '?' : '⚠️'; $payload = json_encode([ 'text' => "$emoji *$level*: $message" ]); $ch = curl_init($this->slackWebhook); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_exec($ch); curl_close($ch); } private function interpolate($message, array $context = array()) { $replace = array(); foreach ($context as $key => $val) { $replace['{' . $key . '}'] = $val; } return strtr($message, $replace); } }</code>
Contoh penggunaan:
<code class="language-php">$logger = new SmartLogger( '/var/log/app.log', 'https://hooks.slack.com/services/YOUR/WEBHOOK/HERE' ); $logger->info('User {user} logged in from {ip}', [ 'user' => 'jonesrussell', 'ip' => '192.168.1.1' ]); $logger->critical('Payment gateway {gateway} is down!', [ 'gateway' => 'Stripe', 'error_code' => 500 ]);</code>
Laravel dan Symfony menyediakan sokongan PSR-3 terbina dalam.
Laravel:
<code class="language-php">public function processOrder($orderId) { try { Log::info('Order processed', ['order_id' => $orderId]); } catch (\Exception $e) { Log::error('Order failed', [ 'order_id' => $orderId, 'error' => $e->getMessage() ]); throw $e; } }</code>
Symfony:
<code class="language-php">class OrderController extends AbstractController { public function process(LoggerInterface $logger, string $orderId) { $logger->info('Starting order process', ['order_id' => $orderId]); // Your code here } }</code>
Siaran ini adalah sebahagian daripada siri tentang piawaian PSR dalam PHP. Topik masa hadapan termasuk PSR-4.
Sumber:
Atas ialah kandungan terperinci Antara Muka PSR-Logger dalam PHP. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!