PSR-Logger Interface in PHP
Ahnii!
Recently, I assisted a team migrating from Monolog to a custom logging solution. Their logging wasn't standardized, requiring code changes across numerous files. This highlights the value of PSR-3, a solution I'll demonstrate here.
Understanding PSR-3 (5 minutes)
PSR-3 acts as a logging contract in PHP. Similar to how a standardized car design ensures ease of operation across different models, PSR-3 provides consistent logging library behavior.
1. The Logger Interface
This contract defines the interface:
<?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. Log Levels (3 minutes)
These levels represent a severity scale:
- Emergency: ? Catastrophic failure (system unusable).
- Alert: ? Requires immediate action.
- Critical: ⚠️ Major component failure.
- Error: ❌ Failure, but system operational.
- Warning: ⚡ Potential problem.
- Notice: ? Normal but significant event.
- Info: ℹ️ Informational message.
- Debug: ? Debugging information.
Real-World Implementation (10 minutes)
Let's create a logger writing to files and sending critical errors to 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); } }
Using It In Your Project (5 minutes)
Example usage:
$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 ]);
Framework Integration (5 minutes)
Laravel and Symfony provide built-in PSR-3 support.
Laravel:
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; } }
Symfony:
class OrderController extends AbstractController { public function process(LoggerInterface $logger, string $orderId) { $logger->info('Starting order process', ['order_id' => $orderId]); // Your code here } }
Quick Tips (2 minutes)
- ? Be Specific: Include detailed context in logs.
- ? Use the Right Level: Avoid overuse of high-severity levels.
Next Steps & Resources
This post is part of a series on PSR standards in PHP. Future topics include PSR-4.
Resources:
- Official PSR-3 Specification
- Monolog Documentation
- Series Example Repository (v0.2.0 - PSR-3 Implementation)
The above is the detailed content of PSR-Logger Interface in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
