VOOZH about

URL: https://deepwiki.com/hypervel/log/5.1-event-system

⇱ Event System | hypervel/log | DeepWiki


Loading...
Menu

Event System

This document describes the event dispatching system integrated into the logging component. Every log message written triggers a MessageLogged event that can be observed by application code. This enables use cases such as real-time log monitoring, metrics collection, alerting, audit logging, and custom log processing without modifying the core logging behavior.

For information about context management and shared logging data, see Contextual Logging. For extending the logging system with custom drivers, see Custom Drivers & Extension.


Overview

The event system is built on the PSR-14 EventDispatcher standard and consists of three main components:

ComponentPurpose
MessageLogged event classImmutable data object containing log level, message, and context
Logger::fireLogEvent()Internal method that dispatches events after each log write
Logger::listen()Public API for registering event listeners

The event dispatcher is optional—if not provided during Logger construction, events are not dispatched and no exceptions are thrown. This allows the logging system to function independently of event infrastructure.

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


MessageLogged Event

The MessageLogged event is a simple data transfer object that carries information about a logged message.

Event Structure


Properties

PropertyTypeDescription
levelstringPSR-3 log level (emergency, alert, critical, error, warning, notice, info, debug)
messagestringFormatted log message after processing by Logger::formatMessage()
contextarrayMerged context array including shared context and call-specific context

The event is immutable—all properties are public readonly (via constructor property promotion). The event contains the final processed data after message formatting and context merging have occurred in src/Logger.php136-144

Sources: src/Events/MessageLogged.php7-18


Event Dispatching Flow

Events are automatically dispatched for every log message written, regardless of which PSR-3 log method is called.

Dispatch Sequence


Implementation Details

The dispatch occurs in the writeLog() method, which is the internal funnel for all PSR-3 log methods:

  1. Message Formatting src/Logger.php139 - Converts objects implementing Jsonable or Arrayable to strings, exports arrays
  2. Context Merging src/Logger.php140 - Combines shared context from Context::get('__logger.context') with call-specific context
  3. Monolog Write src/Logger.php138-141 - Delegates to underlying Monolog logger
  4. Event Dispatch src/Logger.php143 - Calls fireLogEvent() with processed data

The event is dispatched after the log has been written to its destination, ensuring that listeners observe only successfully logged messages.

Sources: src/Logger.php136-144 src/Logger.php204-210


Event Dispatcher Integration

The Logger receives an optional EventDispatcherInterface instance during construction.

Constructor Signature

The Logger constructor accepts two parameters:

Logger::__construct(
 protected LoggerInterface $logger,
 protected ?EventDispatcherInterface $dispatcher = null
)

Defined at src/Logger.php22-26

Dispatcher Requirements

RequirementDescription
InterfaceMust implement Psr\EventDispatcher\EventDispatcherInterface
OptionalLogger functions without dispatcher; events simply won't fire
ImmutabilityCan be set/replaced via setEventDispatcher() at src/Logger.php254-259
RetrievalCan be retrieved via getEventDispatcher() at src/Logger.php244-247

Null-Safe Dispatching

The fireLogEvent() method uses the null-safe operator to conditionally dispatch:

$this->dispatcher?->dispatch(new MessageLogged($level, $message, $context));

This pattern at src/Logger.php209 ensures no errors occur when the dispatcher is null.

Sources: src/Logger.php22-26 src/Logger.php204-210 src/Logger.php244-259


Listening to Log Events

Applications can register event listeners to observe log messages in real-time.

Using Logger::listen()

The Logger class provides a convenience method for registering closures as event listeners:


The implementation at src/Logger.php187-199 validates that:

  1. An event dispatcher has been set
  2. The dispatcher implements a listen() method (framework-specific extension of PSR-14)

Registration Constraints

ConstraintCheck LocationException Message
Dispatcher must existsrc/Logger.php189-191"Events dispatcher has not been set."
Dispatcher must have listen()src/Logger.php193-195"Events dispatcher does not implement the listen method."

The listen() method requirement is noted as framework-specific since PSR-14 doesn't mandate a listen() registration method. This is typically provided by Hyperf's event dispatcher implementation.

Direct Listener Registration

Applications can also register listeners directly with the event dispatcher without using Logger::listen():


This approach bypasses the Logger entirely and works with any PSR-14 compliant event system.

Sources: src/Logger.php187-199


Event Flow Architecture

The following diagram shows how events integrate into the complete logging architecture:


All eight PSR-3 log level methods (emergency, alert, critical, error, warning, notice, info, debug) plus the generic log() and convenience write() methods funnel through the single writeLog() method at src/Logger.php136-144 This ensures consistent event dispatching regardless of which API method is called.

Sources: src/Logger.php29-144


Use Cases

The event system enables several patterns without modifying logging code:

Real-Time Monitoring

Listen for critical/emergency logs to trigger immediate notifications:


Metrics Collection

Aggregate logging statistics without parsing log files:


Audit Trail

Capture sensitive operations logged at specific levels:


Development Debugging

Echo logs to output during development:


Request Correlation

Track all logs for a request using shared context (see Contextual Logging):


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


Integration with Hyperf Event System

When used within Hyperf applications, the Logger receives Hyperf's event dispatcher implementation automatically through dependency injection. The event dispatcher is registered in the service container by the framework and passed to the Logger during instantiation.

Hyperf's event dispatcher extends PSR-14 with the listen() method, enabling the Logger::listen() convenience method at src/Logger.php187-199 Applications can also use Hyperf's @Listener annotation to create dedicated listener classes:


This integration allows the logging system to participate in Hyperf's unified event architecture while remaining PSR-14 compliant for use in other frameworks.

Sources: src/Logger.php12 src/Logger.php24


Summary

The event system provides a decoupled mechanism for observing log activity without modifying logging code or configuration. Key characteristics:

CharacteristicDescription
AutomaticEvery log message triggers an event
OptionalWorks without an event dispatcher
StandardBuilt on PSR-14 EventDispatcherInterface
CompleteContains formatted message and merged context
Post-WriteDispatched after successful log write

This design enables powerful observability and integration patterns while maintaining the simplicity of the core Logger API. The event data includes all processed information (formatted message, merged context) that was actually written to the log destination.

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