PSR-3 Logger Interface
What is PSR-3?
PSR-3 is a PHP standard (PHP Standard Recommendation) that defines a common interface for logging libraries. It allows different logging implementations to be interchangeable.
The LoggerInterface
namespace Psr\Log;
interface LoggerInterface
{
public function emergency(string|\Stringable $message, array $context = []): void;
public function alert(string|\Stringable $message, array $context = []): void;
public function critical(string|\Stringable $message, array $context = []): void;
public function error(string|\Stringable $message, array $context = []): void;
public function warning(string|\Stringable $message, array $context = []): void;
public function notice(string|\Stringable $message, array $context = []): void;
public function info(string|\Stringable $message, array $context = []): void;
public function debug(string|\Stringable $message, array $context = []): void;
public function log($level, string|\Stringable $message, array $context = []): void;
}
Log Levels (Most to Least Severe)
| Level | When to Use |
|---|---|
emergency |
System is unusable, immediate attention needed |
alert |
Action must be taken immediately (e.g., database down) |
critical |
Critical conditions (e.g., payment gateway error) |
error |
Runtime errors (e.g., failed save, API timeout) |
warning |
Unexpected but non-critical (e.g., deprecated usage) |
notice |
Normal but significant (e.g., new admin created) |
info |
Informational (e.g., order placed, cache cleared) |
debug |
Detailed debug info (e.g., SQL queries, variable values) |
Usage
use Psr\Log\LoggerInterface;
class OrderProcessor
{
public function __construct(
private LoggerInterface $logger
) {}
public function process(array $orderData): void
{
$this->logger->info('Processing order', [
'order_id' => $orderData['id'],
'customer' => $orderData['email'],
'total' => $orderData['total'],
]);
try {
$this->createOrder($orderData);
} catch (\Exception $e) {
$this->logger->error('Order processing failed', [
'order_id' => $orderData['id'],
'exception' => $e,
'trace' => $e->getTraceAsString(),
]);
throw $e;
}
}
}
Structured Logging
What is Structured Logging?
Instead of free-form text, structured logging adds context data that can be queried and analyzed:
// BAD: Unstructured
$this->logger->error('Order failed for customer john@example.com with amount $50.00');
// GOOD: Structured
$this->logger->error('Order failed', [
'customer_email' => 'john@example.com',
'amount' => 50.00,
'currency' => 'USD',
'payment_method' => 'credit_card',
'error_code' => 'GATEWAY_TIMEOUT',
'attempt' => 3,
]);
Context Array Keys
Use consistent keys across your application:
// Common context keys
$this->logger->info('Product imported', [
'sku' => 'ABC-123',
'product_id' => 456,
'operation' => 'import',
'source' => 'csv',
'duration_ms' => 150,
'memory_peak_mb' => round(memory_get_peak_usage(true) / 1048576, 2),
]);
// Exception context (PSR-3 standard)
try {
$this->process();
} catch (\Exception $e) {
$this->logger->error('Processing failed', [
'exception' => $e, // PSR-3 knows to format this as stack trace
]);
}
Log Context Best Practices
- Always include identifiers: order_id, product_id, sku
- Include operation context: what was being attempted
- Include timing: duration for performance analysis
- Don't log sensitive data: passwords, credit cards, tokens
- Use consistent key names: snake_case across the application
Magento's Logging System
Magento Logger Setup
Magento uses PSR-3 with Monolog as the implementation:
// Magento\Framework\Logger\Monolog
// This is the default logger in Magento
// Inject via DI
namespace Vendor\Module\Model;
class ProcessManager
{
public function __construct(
private \Psr\Log\LoggerInterface $logger
) {}
public function execute(): void
{
$this->logger->info('Process started');
// ... processing
$this->logger->info('Process completed', ['items_processed' => 100]);
}
}
Magento Log Files
| File | Level | Purpose |
|---|---|---|
var/log/system.log |
All | General system log |
var/log/exception.log |
Error+ | Exceptions only |
var/log/debug.log |
Debug | Detailed debug info |
var/log/cron.log |
All | Cron job output |
Custom Logger Channels
<!-- etc/di.xml -->
<config>
<type name="Magento\Framework\Logger\Monolog">
<arguments>
<argument name="name" xsi:type="string">vendor_module</argument>
<argument name="handlers" xsi:type="array">
<item name="default" xsi:type="object">Magento\Framework\Logger\Handler\Base</item>
<item name="system" xsi:type="object">Magento\Framework\Logger\Handler\System</item>
<item name="debug" xsi:type="object">Magento\Framework\Logger\Handler\Debug</item>
</argument>
</arguments>
</type>
</config>
Logging Performance
// Use log level checks to avoid unnecessary string formatting
if ($this->logger->isHandling(Monolog\Logger::DEBUG)) {
$this->logger->debug('SQL query', [
'query' => $sql, // Expensive string building only when needed
'params' => $params,
]);
}
// Or use lazy evaluation with closures
$this->logger->debug('Complex debug', function () {
return ['data' => $this->expensiveDebugData()];
});
Quiz
1. Which PSR-3 log level should be used for runtime errors like failed saves?
2. Why is structured logging preferred over free-form text?
3. What is PSR-3?
Flashcards
Question
What is PSR-3?
Click to reveal answer
Answer
A PHP standard defining a common LoggerInterface for logging libraries
Question
PSR-3 log levels (most to least severe)?
Click to reveal answer
Answer
emergency, alert, critical, error, warning, notice, info, debug
Question
What is structured logging?
Click to reveal answer
Answer
Logging with context arrays instead of free-form text, enabling querying
Question
Magento default log files?
Click to reveal answer
Answer
system.log (all), exception.log (errors), debug.log (debug)
Revision Notes
Key Takeaways
- 1. PSR-3 defines a standard LoggerInterface for PHP logging
- 2. Log levels: emergency > alert > critical > error > warning > notice > info > debug
- 3. Structured logging uses context arrays for queryable, analyzable logs
- 4. Magento uses Monolog as its PSR-3 implementation
- 5. Log files: system.log, exception.log, debug.log in var/log/
- 6. Check log level before expensive string formatting for performance
Interview Tips
- • Give examples of when to use each log level
- • Explain structured logging benefits (querying, alerting, analysis)
- • Discuss what NOT to log (passwords, credit cards, tokens)
Cheat Sheet
PSR-3 Levels:
emergency → System unusable
alert → Immediate action needed
critical → Critical conditions
error → Runtime errors
warning → Unexpected but non-critical
notice → Normal but significant
info → Informational
debug → Detailed debug info
Structured Logging:
$logger->error('msg', ['key' => 'value']);
Always include: identifiers, operation, timing
Never include: passwords, tokens, PII
Magento: var/log/system.log, exception.log, debug.log