From 984eb5533550602bcb9d0d484c97ae5544240d92 Mon Sep 17 00:00:00 2001 From: Alex Standiford Date: Sun, 25 Jan 2026 12:26:20 -0500 Subject: [PATCH] Add logger package documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Documents the phpnomad/logger package, which provides a logging abstraction layer. Includes: - LoggerStrategy interface - CanLogException trait - Usage examples and integration guide πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .../logger/interfaces/introduction.md | 82 ++++ .../logger/interfaces/logger-strategy.md | 407 ++++++++++++++++++ public/docs/packages/logger/introduction.md | 278 ++++++++++++ .../logger/traits/can-log-exception.md | 238 ++++++++++ .../packages/logger/traits/introduction.md | 82 ++++ 5 files changed, 1087 insertions(+) create mode 100644 public/docs/packages/logger/interfaces/introduction.md create mode 100644 public/docs/packages/logger/interfaces/logger-strategy.md create mode 100644 public/docs/packages/logger/introduction.md create mode 100644 public/docs/packages/logger/traits/can-log-exception.md create mode 100644 public/docs/packages/logger/traits/introduction.md diff --git a/public/docs/packages/logger/interfaces/introduction.md b/public/docs/packages/logger/interfaces/introduction.md new file mode 100644 index 0000000..5d4b1ea --- /dev/null +++ b/public/docs/packages/logger/interfaces/introduction.md @@ -0,0 +1,82 @@ +--- +id: logger-interfaces-introduction +slug: docs/packages/logger/interfaces/introduction +title: Logger Interfaces Overview +doc_type: reference +status: active +language: en +owner: docs-team +last_reviewed: 2026-01-25 +applies_to: ["all"] +canonical: true +summary: Overview of interfaces provided by the logger package. +llm_summary: > + The phpnomad/logger package provides one interface: LoggerStrategy, which defines the + contract for PSR-3 compatible logging throughout PHPNomad applications. This interface + declares methods for all 8 standard log levels plus exception logging. +questions_answered: + - What interfaces does the logger package provide? + - What is the LoggerStrategy interface? +audience: + - developers + - backend engineers +tags: + - logging + - interfaces + - reference +llm_tags: + - logger-strategy + - psr-3 +keywords: + - logger interfaces + - LoggerStrategy +related: + - ../introduction + - ./logger-strategy +see_also: + - ../traits/introduction +noindex: false +--- + +# Logger Interfaces + +The logger package provides one core interface that defines the logging contract for PHPNomad applications. + +--- + +## Available Interfaces + +| Interface | Purpose | +|-----------|---------| +| [LoggerStrategy](./logger-strategy.md) | PSR-3 compatible logging contract with 8 log levels | + +--- + +## Quick Reference + +### LoggerStrategy + +The primary interface for all logging operations: + +```php +use PHPNomad\Logger\Interfaces\LoggerStrategy; + +class MyService +{ + public function __construct(private LoggerStrategy $logger) {} + + public function doSomething(): void + { + $this->logger->info('Operation started'); + } +} +``` + +See [LoggerStrategy](./logger-strategy.md) for complete documentation. + +--- + +## See Also + +- [Logger Package Overview](../introduction.md) - High-level package documentation +- [Logger Traits](../traits/introduction.md) - Default implementations diff --git a/public/docs/packages/logger/interfaces/logger-strategy.md b/public/docs/packages/logger/interfaces/logger-strategy.md new file mode 100644 index 0000000..eab1904 --- /dev/null +++ b/public/docs/packages/logger/interfaces/logger-strategy.md @@ -0,0 +1,407 @@ +--- +id: logger-strategy-interface +slug: docs/packages/logger/interfaces/logger-strategy +title: LoggerStrategy Interface +doc_type: reference +status: active +language: en +owner: docs-team +last_reviewed: 2026-01-25 +applies_to: ["all"] +canonical: true +summary: The LoggerStrategy interface defines a PSR-3 compatible logging contract for PHPNomad applications. +llm_summary: > + LoggerStrategy is the core logging interface in PHPNomad, providing PSR-3 compatible + logging methods for all 8 standard log levels (emergency, alert, critical, error, + warning, notice, info, debug) plus exception logging. Classes implementing this interface + can be swapped without changing application code, enabling flexible logging destinations + (files, databases, external services, null loggers for testing). Each method accepts + a message string and optional context array for structured logging. +questions_answered: + - What is the LoggerStrategy interface? + - What methods does LoggerStrategy define? + - How do I implement LoggerStrategy? + - What parameters does each logging method accept? + - How does logException work? +audience: + - developers + - backend engineers +tags: + - logging + - interface + - psr-3 + - strategy-pattern +llm_tags: + - logger-strategy + - log-levels + - exception-logging +keywords: + - LoggerStrategy + - logging interface + - PSR-3 + - log levels +related: + - ../introduction + - ../traits/can-log-exception +see_also: + - ../../database/introduction + - ../../rest/interceptors/introduction +noindex: false +--- + +# LoggerStrategy Interface + +**Namespace:** `PHPNomad\Logger\Interfaces` + +`LoggerStrategy` defines the logging contract for PHPNomad applications. It follows PSR-3 conventions with methods for all 8 standard log levels plus exception logging. + +--- + +## Interface Definition + +```php +namespace PHPNomad\Logger\Interfaces; + +use Exception; + +interface LoggerStrategy +{ + public function emergency(string $message, array $context = []): void; + public function alert(string $message, array $context = []): void; + public function critical(string $message, array $context = []): void; + public function error(string $message, array $context = []): void; + public function warning(string $message, array $context = []): void; + public function notice(string $message, array $context = []): void; + public function info(string $message, array $context = []): void; + public function debug(string $message, array $context = []): void; + public function logException( + Exception $e, + string $message = '', + array $context = [], + string $level = null + ): mixed; +} +``` + +--- + +## Methods + +### Log Level Methods + +All log level methods share the same signature: + +```php +public function {level}(string $message, array $context = []): void +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `$message` | `string` | The log message | +| `$context` | `array` | Optional structured data to include with the message | + +#### emergency() + +Log when the system is completely unusable. + +```php +$logger->emergency('Database corruption detected', [ + 'table' => 'users', + 'corruption_type' => 'index_mismatch' +]); +``` + +**Use for:** Total system failure, data corruption, situations requiring immediate wake-up calls. + +#### alert() + +Log when immediate action is required. + +```php +$logger->alert('Primary database unreachable', [ + 'host' => $dbHost, + 'failover_active' => true +]); +``` + +**Use for:** Site down, database unavailable, disk full - situations requiring immediate human intervention. + +#### critical() + +Log critical conditions. + +```php +$logger->critical('Payment gateway connection failed', [ + 'gateway' => 'stripe', + 'error_code' => $errorCode +]); +``` + +**Use for:** Component unavailable, unexpected exceptions that affect core functionality. + +#### error() + +Log runtime errors that don't require immediate action. + +```php +$logger->error('Failed to send notification email', [ + 'user_id' => $userId, + 'email' => $email, + 'error' => $e->getMessage() +]); +``` + +**Use for:** Errors that should be investigated but don't halt the system. + +#### warning() + +Log exceptional occurrences that aren't errors. + +```php +$logger->warning('Deprecated API endpoint called', [ + 'endpoint' => '/api/v1/users', + 'replacement' => '/api/v2/users', + 'caller_ip' => $ip +]); +``` + +**Use for:** Deprecated API usage, poor practices, retry successes after failures. + +#### notice() + +Log normal but significant events. + +```php +$logger->notice('Application configuration reloaded', [ + 'config_file' => $configPath, + 'changes' => $changedKeys +]); +``` + +**Use for:** Service startup/shutdown, configuration changes, significant state changes. + +#### info() + +Log interesting events. + +```php +$logger->info('User logged in', [ + 'user_id' => $userId, + 'ip_address' => $ip, + 'user_agent' => $userAgent +]); +``` + +**Use for:** User actions, successful operations, routine events worth recording. + +#### debug() + +Log detailed debugging information. + +```php +$logger->debug('SQL query executed', [ + 'query' => $sql, + 'bindings' => $bindings, + 'duration_ms' => $duration +]); +``` + +**Use for:** Variable dumps, execution flow, detailed diagnostics. Typically disabled in production. + +--- + +### logException() + +Log an exception with configurable severity level. + +```php +public function logException( + Exception $e, + string $message = '', + array $context = [], + string $level = null +): mixed; +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `$e` | `Exception` | The exception to log | +| `$message` | `string` | Optional additional message | +| `$context` | `array` | Optional structured context data | +| `$level` | `string\|null` | Log level to use (defaults to `critical`) | + +**Example:** + +```php +try { + $this->processPayment($order); +} catch (PaymentException $e) { + $this->logger->logException( + $e, + 'Payment processing failed', + ['order_id' => $order->getId()], + LoggerLevel::Error + ); + throw $e; +} +``` + +The default implementation (via [CanLogException trait](../traits/can-log-exception.md)) combines your message with the exception message and calls the appropriate level method. + +--- + +## Log Level Severity + +From most to least severe: + +``` +EMERGENCY β†’ System is unusable + ↓ + ALERT β†’ Immediate action required + ↓ +CRITICAL β†’ Critical conditions + ↓ + ERROR β†’ Runtime errors + ↓ + WARNING β†’ Exceptional but not errors + ↓ + NOTICE β†’ Normal but significant + ↓ + INFO β†’ Interesting events + ↓ + DEBUG β†’ Detailed debug info +``` + +--- + +## Implementing LoggerStrategy + +### Basic Implementation + +```php +use PHPNomad\Logger\Interfaces\LoggerStrategy; +use PHPNomad\Logger\Traits\CanLogException; +use PHPNomad\Logger\Enums\LoggerLevel; + +class FileLogger implements LoggerStrategy +{ + use CanLogException; + + public function __construct(private string $logFile) {} + + public function emergency(string $message, array $context = []): void + { + $this->write(LoggerLevel::Emergency, $message, $context); + } + + public function alert(string $message, array $context = []): void + { + $this->write(LoggerLevel::Alert, $message, $context); + } + + public function critical(string $message, array $context = []): void + { + $this->write(LoggerLevel::Critical, $message, $context); + } + + public function error(string $message, array $context = []): void + { + $this->write(LoggerLevel::Error, $message, $context); + } + + public function warning(string $message, array $context = []): void + { + $this->write(LoggerLevel::Warning, $message, $context); + } + + public function notice(string $message, array $context = []): void + { + $this->write(LoggerLevel::Notice, $message, $context); + } + + public function info(string $message, array $context = []): void + { + $this->write(LoggerLevel::Info, $message, $context); + } + + public function debug(string $message, array $context = []): void + { + $this->write(LoggerLevel::Debug, $message, $context); + } + + private function write(string $level, string $message, array $context): void + { + $timestamp = date('Y-m-d H:i:s'); + $contextJson = empty($context) ? '' : ' ' . json_encode($context); + $line = "[{$timestamp}] [{$level}] {$message}{$contextJson}\n"; + + file_put_contents($this->logFile, $line, FILE_APPEND | LOCK_EX); + } +} +``` + +### Null Logger for Testing + +```php +class NullLogger implements LoggerStrategy +{ + use CanLogException; + + public function emergency(string $message, array $context = []): void {} + public function alert(string $message, array $context = []): void {} + public function critical(string $message, array $context = []): void {} + public function error(string $message, array $context = []): void {} + public function warning(string $message, array $context = []): void {} + public function notice(string $message, array $context = []): void {} + public function info(string $message, array $context = []): void {} + public function debug(string $message, array $context = []): void {} +} +``` + +--- + +## Usage Examples + +### Dependency Injection + +```php +class OrderService +{ + public function __construct(private LoggerStrategy $logger) {} + + public function processOrder(Order $order): void + { + $this->logger->info('Processing order', [ + 'order_id' => $order->getId(), + 'total' => $order->getTotal() + ]); + + // Process... + + $this->logger->info('Order completed', [ + 'order_id' => $order->getId() + ]); + } +} +``` + +### With Context Arrays + +```php +// Use structured context instead of string interpolation +$this->logger->info('User action', [ + 'user_id' => $userId, + 'action' => 'login', + 'ip_address' => $request->getClientIp(), + 'timestamp' => time() +]); +``` + +--- + +## See Also + +- [CanLogException Trait](../traits/can-log-exception.md) - Default `logException()` implementation +- [Logger Package Overview](../introduction.md) - High-level documentation +- [Database Package](../../database/introduction.md) - Uses LoggerStrategy for query logging +- [REST Interceptors](../../rest/interceptors/introduction.md) - Request/response logging diff --git a/public/docs/packages/logger/introduction.md b/public/docs/packages/logger/introduction.md new file mode 100644 index 0000000..c62ffd5 --- /dev/null +++ b/public/docs/packages/logger/introduction.md @@ -0,0 +1,278 @@ +--- +id: logger-introduction +slug: docs/packages/logger/introduction +title: Logger Package +doc_type: explanation +status: active +language: en +owner: docs-team +last_reviewed: 2026-01-25 +applies_to: ["all"] +canonical: true +summary: The logger package provides a PSR-3 compatible logging interface for consistent logging across PHPNomad applications. +llm_summary: > + phpnomad/logger provides the LoggerStrategy interface and CanLogException trait for consistent + logging throughout PHPNomad applications. The interface follows PSR-3 conventions with 8 log + levels (emergency, alert, critical, error, warning, notice, info, debug) plus exception logging. + The CanLogException trait provides a default implementation for logging exceptions with + configurable severity levels. This is an abstraction package - it defines the logging contract + but implementations come from integration packages or application code. Used extensively by + database, cache, REST, datastore packages and throughout the framework for error tracking, + debugging, and audit logging. +questions_answered: + - What is the logger package? + - How do I implement logging in PHPNomad? + - What log levels are available? + - How do I log exceptions? +audience: + - developers + - backend engineers + - devops +tags: + - logging + - psr-3 + - interface + - strategy-pattern +llm_tags: + - logger-strategy + - log-levels + - exception-logging + - can-log-exception +keywords: + - phpnomad logger + - logging interface + - psr-3 logging + - log levels php + - exception logging +related: + - ../database/introduction + - ../cache/introduction + - ../singleton/introduction +see_also: + - ../rest/interceptors/introduction + - ../datastore/introduction +noindex: false +--- + +# Logger + +`phpnomad/logger` provides a **PSR-3 compatible logging interface** for consistent logging across PHPNomad applications. It defines the logging contractβ€”implementations are provided by integration packages or your application code. + +At its core: + +* **PSR-3 compatible** β€” Eight standard log levels matching the widely-adopted standard +* **Strategy pattern** β€” Swap logging implementations without changing application code +* **Exception logging** β€” Built-in support for logging exceptions with stack traces +* **Zero dependencies** β€” Pure abstraction with no external requirements + +--- + +## Key ideas at a glance + +| Component | Purpose | +|-----------|---------| +| [LoggerStrategy](./interfaces/logger-strategy.md) | Interface defining all logging methods | +| [CanLogException](./traits/can-log-exception.md) | Trait providing default exception logging | +| LoggerLevel | Constants for the 8 standard log levels | + +--- + +## Why this package exists + +Applications need consistent logging, but logging destinations vary: + +| Environment | Typical destination | +|-------------|-------------------| +| Development | Console/stdout | +| Production | File, database, or log service | +| WordPress | `error_log()` or WP debug.log | +| Testing | In-memory or null logger | + +Without a common interface, code becomes tied to specific loggers. With LoggerStrategy, you can swap implementations without changing application code. + +--- + +## Installation + +```bash +composer require phpnomad/logger +``` + +**Requirements:** PHP 7.4+ + +**Dependencies:** None (zero dependencies) + +--- + +## Log levels + +The eight standard log levels, from most to least severe: + +``` +SEVERITY HIERARCHY (highest to lowest) +══════════════════════════════════════ + + EMERGENCY System is unusable + β”‚ (total failure, data corruption) + β–Ό + ALERT Immediate action required + β”‚ (site down, database unavailable) + β–Ό + CRITICAL Critical conditions + β”‚ (component unavailable, unexpected exception) + β–Ό + ERROR Runtime errors + β”‚ (errors that don't require immediate action) + β–Ό + WARNING Exceptional occurrences that aren't errors + β”‚ (deprecated APIs, poor API usage) + β–Ό + NOTICE Normal but significant events + β”‚ (startup, shutdown, config changes) + β–Ό + INFO Interesting events + β”‚ (user actions, SQL queries, API calls) + β–Ό + DEBUG Detailed debug information + (variable dumps, execution flow) +``` + +--- + +## Basic usage + +Inject `LoggerStrategy` and call the appropriate level method: + +```php +use PHPNomad\Logger\Interfaces\LoggerStrategy; + +class OrderService +{ + public function __construct(private LoggerStrategy $logger) {} + + public function processOrder(Order $order): void + { + $this->logger->info('Processing order', [ + 'order_id' => $order->getId(), + 'customer' => $order->getCustomerId() + ]); + + try { + $this->chargePayment($order); + } catch (PaymentException $e) { + $this->logger->error('Payment failed', [ + 'order_id' => $order->getId(), + 'error' => $e->getMessage() + ]); + throw $e; + } + } +} +``` + +See [LoggerStrategy](./interfaces/logger-strategy.md) for complete API documentation. + +--- + +## When to use each level + +| Level | Use when... | Examples | +|-------|-------------|----------| +| Emergency | System is completely unusable | Data corruption, total failure | +| Alert | Immediate human action required | Database down, disk full | +| Critical | Critical component failed | Payment gateway unreachable | +| Error | Something failed but system continues | Failed API call, validation error | +| Warning | Something unexpected but not an error | Deprecated API used, slow query | +| Notice | Normal but notable events | Service started, config reloaded | +| Info | Routine operations worth recording | User login, order placed | +| Debug | Detailed debugging info | Variable dumps, SQL queries | + +--- + +## Best practices + +### Use structured context + +```php +// Bad - string interpolation +$this->logger->info("Order {$orderId} created by user {$userId}"); + +// Good - structured context +$this->logger->info('Order created', [ + 'order_id' => $orderId, + 'user_id' => $userId +]); +``` + +### Don't log sensitive data + +```php +// Bad - logging passwords +$this->logger->info('User login', ['password' => $password]); + +// Good - redact sensitive fields +$this->logger->info('User login', ['username' => $username]); +``` + +### Log at appropriate levels + +```php +$this->logger->error('User not found'); // Bad - not an error +$this->logger->info('User not found'); // Good - expected behavior +``` + +--- + +## Package contents + +### Interfaces + +| Interface | Description | +|-----------|-------------| +| [LoggerStrategy](./interfaces/logger-strategy.md) | PSR-3 compatible logging contract | + +See [Interfaces Overview](./interfaces/introduction.md) for details. + +### Traits + +| Trait | Description | +|-------|-------------| +| [CanLogException](./traits/can-log-exception.md) | Default `logException()` implementation | + +See [Traits Overview](./traits/introduction.md) for details. + +### Enums + +| Enum | Description | +|------|-------------| +| LoggerLevel | Constants for all 8 log levels | + +--- + +## Relationship to other packages + +### Packages that use logger + +| Package | How it uses LoggerStrategy | +|---------|---------------------------| +| [database](../database/introduction.md) | Logs query errors and operations | +| [cache](../cache/introduction.md) | Logs cache misses and errors | +| [rest](../rest/introduction.md) | Request/response logging via interceptors | +| [datastore](../datastore/introduction.md) | Operation logging in decorators | +| [facade](../facade/introduction.md) | LogService facade wraps LoggerStrategy | + +### Related packages + +| Package | Relationship | +|---------|-------------| +| [singleton](../singleton/introduction.md) | Logger instances often use singleton pattern | +| [di](../di/introduction.md) | Logger typically registered in container | + +--- + +## Next steps + +* **[LoggerStrategy Interface](./interfaces/logger-strategy.md)** β€” Complete interface documentation +* **[CanLogException Trait](./traits/can-log-exception.md)** β€” Default exception logging +* **[Database Package](../database/introduction.md)** β€” See query logging in action +* **[REST Interceptors](../rest/interceptors/introduction.md)** β€” Request/response logging diff --git a/public/docs/packages/logger/traits/can-log-exception.md b/public/docs/packages/logger/traits/can-log-exception.md new file mode 100644 index 0000000..8679be9 --- /dev/null +++ b/public/docs/packages/logger/traits/can-log-exception.md @@ -0,0 +1,238 @@ +--- +id: can-log-exception-trait +slug: docs/packages/logger/traits/can-log-exception +title: CanLogException Trait +doc_type: reference +status: active +language: en +owner: docs-team +last_reviewed: 2026-01-25 +applies_to: ["all"] +canonical: true +summary: The CanLogException trait provides a default implementation for logging exceptions in LoggerStrategy implementations. +llm_summary: > + CanLogException is a trait that provides the default implementation of the logException() + method for classes implementing LoggerStrategy. It combines the provided message with + the exception message, defaults to critical severity level, and dynamically calls the + appropriate log level method. This reduces boilerplate when creating custom logger + implementations. +questions_answered: + - What is the CanLogException trait? + - How does CanLogException implement logException? + - What is the default log level for exceptions? + - How do I use CanLogException in my logger? +audience: + - developers + - backend engineers +tags: + - logging + - trait + - exception-handling +llm_tags: + - can-log-exception + - exception-logging + - default-implementation +keywords: + - CanLogException + - exception logging + - logger trait +related: + - ../introduction + - ../interfaces/logger-strategy +see_also: + - ../../database/introduction +noindex: false +--- + +# CanLogException Trait + +**Namespace:** `PHPNomad\Logger\Traits` + +`CanLogException` provides a default implementation of the `logException()` method for classes implementing `LoggerStrategy`. Use this trait to avoid writing boilerplate exception logging code. + +--- + +## Trait Definition + +```php +namespace PHPNomad\Logger\Traits; + +use Exception; +use PHPNomad\Logger\Enums\LoggerLevel; + +trait CanLogException +{ + public function logException( + Exception $e, + string $message = '', + array $context = [], + $level = null + ) { + if (!$level) { + $level = LoggerLevel::Critical; + } + + $this->$level( + implode(' - ', [$message, $e->getMessage()]), + $context + ); + } +} +``` + +--- + +## Behavior + +| Aspect | Behavior | +|--------|----------| +| Default level | `critical` if no level specified | +| Message format | Combines your message with exception message using ` - ` separator | +| Method dispatch | Dynamically calls the appropriate level method (`$this->$level(...)`) | + +### Output Format + +When you call: + +```php +$logger->logException( + $exception, + 'Payment failed', + ['order_id' => 123], + LoggerLevel::Error +); +``` + +The trait produces a log entry like: + +``` +[2026-01-25 10:30:45] [error] Payment failed - Card was declined {"order_id": 123} +``` + +--- + +## Usage + +### Basic Usage + +```php +use PHPNomad\Logger\Interfaces\LoggerStrategy; +use PHPNomad\Logger\Traits\CanLogException; + +class FileLogger implements LoggerStrategy +{ + use CanLogException; + + // Implement the 8 log level methods... + public function emergency(string $message, array $context = []): void + { + $this->write('emergency', $message, $context); + } + + // ... other level methods + + private function write(string $level, string $message, array $context): void + { + // Write to file + } +} +``` + +With the trait, `logException()` is automatically available: + +```php +$logger = new FileLogger('/var/log/app.log'); + +try { + riskyOperation(); +} catch (Exception $e) { + $logger->logException($e, 'Operation failed'); +} +``` + +### Specifying Log Level + +```php +use PHPNomad\Logger\Enums\LoggerLevel; + +// Default: critical +$logger->logException($e, 'Something went wrong'); + +// Explicit level +$logger->logException($e, 'User input error', [], LoggerLevel::Warning); +$logger->logException($e, 'Database error', [], LoggerLevel::Error); +$logger->logException($e, 'Fatal failure', [], LoggerLevel::Emergency); +``` + +### With Context + +```php +try { + $this->processOrder($order); +} catch (PaymentException $e) { + $this->logger->logException( + $e, + 'Payment processing failed', + [ + 'order_id' => $order->getId(), + 'customer_id' => $order->getCustomerId(), + 'amount' => $order->getTotal() + ], + LoggerLevel::Error + ); +} +``` + +--- + +## Overriding the Implementation + +If you need different behavior, you can override the method in your logger class: + +```php +class CustomLogger implements LoggerStrategy +{ + use CanLogException { + logException as protected defaultLogException; + } + + public function logException( + Exception $e, + string $message = '', + array $context = [], + $level = null + ) { + // Add stack trace to context + $context['stack_trace'] = $e->getTraceAsString(); + $context['exception_class'] = get_class($e); + $context['file'] = $e->getFile(); + $context['line'] = $e->getLine(); + + $this->defaultLogException($e, $message, $context, $level); + } +} +``` + +--- + +## Requirements + +The trait requires that your class implements all 8 log level methods from `LoggerStrategy`: + +- `emergency(string $message, array $context = []): void` +- `alert(string $message, array $context = []): void` +- `critical(string $message, array $context = []): void` +- `error(string $message, array $context = []): void` +- `warning(string $message, array $context = []): void` +- `notice(string $message, array $context = []): void` +- `info(string $message, array $context = []): void` +- `debug(string $message, array $context = []): void` + +The trait dynamically calls `$this->$level()`, so all level methods must exist. + +--- + +## See Also + +- [LoggerStrategy Interface](../interfaces/logger-strategy.md) - The interface this trait helps implement +- [Logger Package Overview](../introduction.md) - High-level documentation diff --git a/public/docs/packages/logger/traits/introduction.md b/public/docs/packages/logger/traits/introduction.md new file mode 100644 index 0000000..548f786 --- /dev/null +++ b/public/docs/packages/logger/traits/introduction.md @@ -0,0 +1,82 @@ +--- +id: logger-traits-introduction +slug: docs/packages/logger/traits/introduction +title: Logger Traits Overview +doc_type: reference +status: active +language: en +owner: docs-team +last_reviewed: 2026-01-25 +applies_to: ["all"] +canonical: true +summary: Overview of traits provided by the logger package. +llm_summary: > + The phpnomad/logger package provides one trait: CanLogException, which offers a default + implementation for the logException method defined in LoggerStrategy. This trait can be + used by any class implementing LoggerStrategy to get exception logging behavior without + writing it from scratch. +questions_answered: + - What traits does the logger package provide? + - What is the CanLogException trait? +audience: + - developers + - backend engineers +tags: + - logging + - traits + - reference +llm_tags: + - can-log-exception + - exception-logging +keywords: + - logger traits + - CanLogException +related: + - ../introduction + - ./can-log-exception +see_also: + - ../interfaces/introduction +noindex: false +--- + +# Logger Traits + +The logger package provides one trait that helps when implementing the LoggerStrategy interface. + +--- + +## Available Traits + +| Trait | Purpose | +|-------|---------| +| [CanLogException](./can-log-exception.md) | Default implementation for exception logging | + +--- + +## Quick Reference + +### CanLogException + +Provides a default `logException()` implementation: + +```php +use PHPNomad\Logger\Interfaces\LoggerStrategy; +use PHPNomad\Logger\Traits\CanLogException; + +class MyLogger implements LoggerStrategy +{ + use CanLogException; + + // Only need to implement the 8 level methods + // logException() is provided by the trait +} +``` + +See [CanLogException](./can-log-exception.md) for complete documentation. + +--- + +## See Also + +- [Logger Package Overview](../introduction.md) - High-level package documentation +- [Logger Interfaces](../interfaces/introduction.md) - Interface documentation