阿尼!
最近,我协助一个团队从 Monolog 迁移到自定义日志记录解决方案。 他们的日志记录没有标准化,需要跨多个文件更改代码。 这凸显了 PSR-3 的价值,我将在此演示该解决方案。
PSR-3 充当 PHP 中的日志合约。 与标准化汽车设计如何确保不同车型的易用性类似,PSR-3 提供一致的日志记录库行为。
该合约定义了接口:
<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>
这些级别代表严重程度:
让我们创建一个记录器写入文件并将严重错误发送到 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>
用法示例:
<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 和 Symfony 提供内置的 PSR-3 支持。
拉拉维尔:
<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>
交响乐:
<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>
这篇文章是 PHP PSR 标准系列的一部分。 未来的主题包括 PSR-4。
资源:
以上是PHP 中的 PSR 记录器接口的详细内容。更多信息请关注PHP中文网其他相关文章!