阿尼!
最近,我協助一個團隊從 Monolog 遷移到自訂日誌記錄解決方案。 他們的日誌記錄沒有標準化,需要跨多個文件更改代碼。 這凸顯了 PSR-3 的價值,我將在此示範解決方案。
了解 PSR-3(5 分鐘)
PSR-3 充當 PHP 中的日誌合約。 與標準化汽車設計如何確保不同車型的易用性類似,PSR-3 提供一致的日誌記錄庫行為。
1.記錄器介面
此合約定義了介面:
<?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()); } ?>
2.日誌等級(3 分鐘)
這些等級代表嚴重程度:
- 緊急狀況:?災難性故障(系統無法使用)。
- 警報:?需要立即採取行動。
- 嚴重:⚠️主要組件故障。
- 錯誤:❌失敗,但係統可運作。
- 警告:⚡潛在問題。
- 注意:?正常但意義重大的事件。
- 訊息:ℹ️資訊性訊息。
- 調試:?調試資訊。
實際實施(10 分鐘)
讓我們建立一個記錄器寫入檔案並將嚴重錯誤傳送到 Slack:
<?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); } }
在您的專案中使用它(5 分鐘)
用法範例:
$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 ]);
框架整合(5 分鐘)
Laravel 和 Symfony 提供內建的 PSR-3 支援。
拉拉維爾:
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; } }
交響樂:
class OrderController extends AbstractController { public function process(LoggerInterface $logger, string $orderId) { $logger->info('Starting order process', ['order_id' => $orderId]); // Your code here } }
快速提示(2 分鐘)
- ? 具體:在日誌中包含詳細的上下文。
- ? 使用正確的等級:避免過度使用高嚴重程度。
後續步驟與資源
這篇文章是 PHP PSR 標準系列的一部分。 未來的主題包括 PSR-4。
資源:
- PSR-3 官方規範
- 獨白文件
- 系列範例儲存庫(v0.2.0 - PSR-3 實作)
以上是PHP 中的 PSR 記錄器接口的詳細內容。更多資訊請關注PHP中文網其他相關文章!

phpIdentifiesauser'ssessionSessionSessionCookiesAndSessionId.1)whiwsession_start()被稱為,phpgeneratesainiquesesesessionIdStoredInacookInAcookInAcienamedInAcienamedphpsessIdontheuser'sbrowser'sbrowser.2)thisIdallowSphptpptpptpptpptpptpptpptoretoreteretrieetrieetrieetrieetrieetrieetreetrieetrieetrieetrieetremthafromtheserver。

PHP會話的安全可以通過以下措施實現:1.使用session_regenerate_id()在用戶登錄或重要操作時重新生成會話ID。 2.通過HTTPS協議加密傳輸會話ID。 3.使用session_save_path()指定安全目錄存儲會話數據,並正確設置權限。

phpsessionFilesArestoredIntheDirectorySpecifiedBysession.save_path,通常是/tmponunix-likesystemsorc:\ windows \ windows \ temponwindows.tocustomizethis:tocustomizEthis:1)useession_save_save_save_path_path()

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

利用會話構建高效購物車系統的步驟包括:1)理解會話的定義與作用,會話是服務器端的存儲機制,用於跨請求維護用戶狀態;2)實現基本的會話管理,如添加商品到購物車;3)擴展到高級用法,支持商品數量管理和刪除;4)優化性能和安全性,通過持久化會話數據和使用安全的會話標識符。

本文討論了PHP中的crypt()和password_hash()的差異,以進行密碼哈希,重點介紹其實施,安全性和對現代Web應用程序的適用性。

文章討論了通過輸入驗證,輸出編碼以及使用OWASP ESAPI和HTML淨化器之類的工具來防止PHP中的跨站點腳本(XSS)。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3漢化版
中文版,非常好用

記事本++7.3.1
好用且免費的程式碼編輯器

Dreamweaver Mac版
視覺化網頁開發工具