VOOZH about

URL: https://deepwiki.com/hypervel/log/2.2-logger:-psr-3-wrapper

⇱ Logger: PSR-3 Wrapper | hypervel/log | DeepWiki


Loading...
Menu

Logger: PSR-3 Wrapper

Purpose and Scope

The Logger class serves as a PSR-3 compliant wrapper around Monolog loggers, adding Hyperf-specific functionality to the standard logging interface. This class is the primary interface through which application code writes log messages. It extends basic PSR-3 logging with three key enhancements: coroutine-safe contextual logging via Hyperf's Context system, automatic event dispatching for every log message, and intelligent message formatting for Hyperf types.

For information about how Logger instances are created and managed, see LogManager: Channel Factory & Manager. For details on the event system, see Event System. For context management features, see Contextual Logging.


Class Structure and Dependencies

The Logger class implements Psr\Log\LoggerInterface and acts as a decorator around another PSR-3 logger (typically a Monolog logger). It maintains two dependencies injected via constructor: the underlying logger and an optional event dispatcher.


Key Relationships:

ComponentRelationshipPurpose
LoggerInterfaceImplemented byEnsures PSR-3 compliance
Underlying LoggerInterfaceWrapped/decoratedDelegates actual logging to Monolog
EventDispatcherInterfaceOptional dependencyDispatches MessageLogged events
Hyperf\Context\ContextStatic utilityStores shared context data
MessageLoggedCreated byEvent object for log messages

Sources: src/Logger.php1-272 src/Events/MessageLogged.php1-18


PSR-3 Interface Implementation

The Logger class implements all eight standard PSR-3 log level methods plus the generic log() method. Each method delegates to the protected writeLog() method, which orchestrates the complete logging operation.


Log Level Methods

All PSR-3 log level methods follow the same pattern:

MethodLog LevelLine Reference
emergency()Emergencysrc/Logger.php33-36
alert()Alertsrc/Logger.php43-46
critical()Criticalsrc/Logger.php53-56
error()Errorsrc/Logger.php63-66
warning()Warningsrc/Logger.php73-76
notice()Noticesrc/Logger.php83-86
info()Infosrc/Logger.php93-96
debug()Debugsrc/Logger.php103-106

Each method accepts a string|Stringable $message and an optional array $context, then calls writeLog(__FUNCTION__, $message, $context) to perform the actual logging operation.

Additional Logging Methods

Beyond the standard PSR-3 methods, Logger provides:

  • write($level, $message, $context) src/Logger.php125-128: Alternative method name for logging, provides API compatibility with frameworks that use this convention
  • log($level, $message, $context) src/Logger.php114-117: Generic PSR-3 log method that accepts the level as a parameter

Sources: src/Logger.php33-128


Core Logging Flow

The writeLog() method orchestrates the complete logging operation, executing five distinct steps for every log message.


writeLog Method Implementation

The writeLog() method src/Logger.php136-144 performs the following operations:

  1. Format Message: Calls formatMessage() to convert the message into a loggable string format
  2. Retrieve Shared Context: Calls getContext() to retrieve coroutine-scoped shared context from Hyperf Context
  3. Merge Contexts: Combines shared context with the provided context array (provided context takes precedence)
  4. Delegate to Underlying Logger: Calls the corresponding method on the wrapped Monolog logger using dynamic method invocation: $this->logger->{$level}(...)
  5. Fire Event: Dispatches a MessageLogged event with the level, message, and merged context

This architecture ensures that every log operation benefits from shared context and triggers events, without requiring explicit handling by application code.

Sources: src/Logger.php136-144


Message Formatting

The formatMessage() method src/Logger.php218-231 provides intelligent formatting for various Hyperf and PHP types, ensuring that complex data structures can be logged effectively.

Supported Message Types

Input TypeFormatting BehaviorExample
string or StringablePass through unchanged"Payment failed"
arrayConvert via var_export($message, true)Array becomes PHP code representation
JsonableCall __toString() via castConverts to JSON string
ArrayableCall toArray(), then var_export()Collection becomes PHP array representation

Formatting Logic Flow


This formatting system allows logging of Hyperf collections, models, and other framework objects without requiring manual serialization.

Sources: src/Logger.php218-231


Context Management

The Logger class provides a coroutine-safe context management system using Hyperf's Context facility. Shared context is stored under the key __logger.context and is automatically included in every log message.

Context Storage Architecture


Context Methods

withContext(array $context): self

src/Logger.php151-158 - Adds context data to the shared context, merging with any existing context. Uses Context::override() to ensure atomic updates in coroutine environments.


The method uses a closure with Context::override() to safely merge new context with existing context:


Returns $this for method chaining.

withoutContext(): self

src/Logger.php165-170 - Clears all shared context by destroying the context key. Returns $this for method chaining.

getContext(): array

src/Logger.php177-180 - Retrieves the current shared context array from Hyperf Context. Returns an empty array if no context is set.

Context Merging Behavior

When writeLog() merges contexts src/Logger.php140 the provided context takes precedence:


This means:

  • Shared context provides defaults
  • Method-specific context overrides shared values
  • Both are included in the final log entry

Sources: src/Logger.php151-180


Event Dispatching

Every log message triggers a MessageLogged event, enabling decoupled monitoring, metrics collection, and alerting systems.

Event Dispatching Flow


MessageLogged Event

src/Events/MessageLogged.php1-18 - Simple data transfer object containing:

PropertyTypeDescription
levelstringPSR-3 log level (emergency, alert, critical, error, warning, notice, info, debug)
messagestringFormatted log message
contextarrayMerged context array

Event Methods

fireLogEvent(string $level, string $message, array $context): void

src/Logger.php204-210 - Protected method that dispatches the event. Uses null-safe operator (?->) to gracefully handle cases where no event dispatcher is configured:


listen(Closure $callback): void

src/Logger.php187-199 - Registers a callback to be invoked when log events occur. This method:

  1. Verifies an event dispatcher is configured (throws RuntimeException if not)
  2. Verifies the dispatcher implements a listen() method (throws RuntimeException if not)
  3. Registers the callback as a listener for MessageLogged::class

Note: This method is framework-specific and relies on the event dispatcher implementing a non-standard listen() method. It is marked with @phpstan-ignore-next-line due to this non-PSR-14 requirement.

Event Dispatcher Configuration

The event dispatcher is:

Sources: src/Logger.php187-210 src/Events/MessageLogged.php1-18


Proxy Pattern and Extensibility

The Logger class implements the proxy pattern, allowing direct access to the underlying Monolog logger's methods when needed.

Magic Method Delegation

The __call() magic method src/Logger.php268-271 forwards any undefined method calls directly to the wrapped logger:


This enables:

  • Access to Monolog-specific methods without explicit wrapper methods
  • Extension of functionality by the underlying logger
  • Transparent proxying of any custom methods added to Monolog

Logger Access Methods

getLogger(): LoggerInterface

src/Logger.php236-239 - Returns the underlying PSR-3 logger instance (typically a Monolog logger). Useful when direct access to Monolog functionality is required.


Method Call Resolution Priority

When a method is called on Logger:

  1. Direct methods: If Logger defines the method, it is called
  2. PSR-3 methods: Standard logging methods are handled by Logger
  3. Magic proxy: Undefined methods are forwarded to underlying logger via __call()

This architecture provides a clean separation: Logger adds Hyperf-specific features while allowing full access to Monolog's capabilities when needed.

Sources: src/Logger.php236-271


Constructor and Dependency Injection

The Logger class constructor src/Logger.php22-26 accepts two dependencies:

ParameterTypeRequiredPurpose
$loggerLoggerInterfaceYesUnderlying PSR-3 logger (typically Monolog) to wrap
$dispatcherEventDispatcherInterfaceNoOptional event dispatcher for firing MessageLogged events

Both dependencies are stored as protected properties, making them accessible to subclasses but not public API.


The LogManager typically instantiates Logger instances with:

  • A configured Monolog logger as the first parameter
  • The container-resolved event dispatcher as the second parameter

Sources: src/Logger.php22-26


Summary

The Logger class serves as an enhanced PSR-3 wrapper that:

  1. Maintains PSR-3 Compliance: Implements all standard logging methods with proper signatures
  2. Adds Hyperf Integration: Uses Hyperf\Context\Context for coroutine-safe shared context management
  3. Enables Event-Driven Architecture: Dispatches MessageLogged events for every log operation
  4. Provides Smart Formatting: Automatically formats Hyperf types (Jsonable, Arrayable) for logging
  5. Preserves Extensibility: Proxies undefined methods to the underlying logger via __call()

This architecture allows the logging system to provide powerful framework-specific features while maintaining compatibility with the PSR-3 standard and the underlying Monolog implementation.

Sources: src/Logger.php1-272 src/Events/MessageLogged.php1-18

Refresh this wiki

On this page