VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/2-sentry-error-tracking-and-performance-monitoring

⇱ Sentry Error Tracking and Performance Monitoring | friendsofhyperf/components | DeepWiki


Loading...
Last indexed: 14 February 2026 (15d5ca)
Menu

Sentry Error Tracking and Performance Monitoring

The Sentry component provides comprehensive error tracking and performance monitoring for Hyperf applications. It integrates the official sentry/sentry SDK with Hyperf's event system, AOP framework, and coroutine architecture to automatically instrument application operations and capture errors, exceptions, and performance metrics. The component supports distributed tracing across HTTP requests, console commands, cron jobs, message queues (AsyncQueue, AMQP, Kafka), RPC calls, and database operations.

For information about the Telescope debug assistant component which provides local debugging capabilities, see page 9.

Sources: src/sentry/publish/sentry.php1-186 src/sentry/src/ConfigProvider.php1-93 CHANGELOG-3.1.md1-451


Architecture Overview

The Sentry integration consists of three primary layers: configuration and initialization, instrumentation and observation, and data transmission.


Sources: src/sentry/src/ConfigProvider.php16-92 src/sentry/src/Tracing/Listener/EventHandleListener.php1-754


Configuration Structure

The component is configured through config/autoload/sentry.php with over 40 environment-variable-backed settings organized into logical sections.

Core Settings

Configuration KeyEnvironment VariableDefaultPurpose
dsnSENTRY_DSN''Sentry project DSN
releaseSENTRY_RELEASEnullApplication version
environmentAPP_ENV'production'Deployment environment
sample_rateSENTRY_SAMPLE_RATE1.0Error sampling rate
traces_sample_rateSENTRY_TRACES_SAMPLE_RATE1.0Transaction sampling rate
profiles_sample_rateSENTRY_PROFILES_SAMPLE_RATEnullProfiling sampling rate

Integration Toggles

The enable array controls whether specific integration modules are active:


Tracing Configuration

The tracing and tracing_spans arrays provide fine-grained control over performance instrumentation:


The tracing_tags array controls whether sensitive data is included in span tags:


Sources: src/sentry/publish/sentry.php13-186


Feature Flag System

The Feature class (src/sentry/src/Feature.php1-133) provides a centralized API for checking configuration flags at runtime.


Key Methods

MethodPurposeExample Usage
isEnabled(string $key, bool $default)Check if integration is enabled$feature->isEnabled('amqp')
isBreadcrumbEnabled(string $key)Check if breadcrumb capture is enabled$feature->isBreadcrumbEnabled('cache')
isTracingEnabled(string $key)Check if transaction tracing is enabled$feature->isTracingEnabled('request')
isTracingSpanEnabled(string $key)Check if span creation is enabled$feature->isTracingSpanEnabled('db')
isTracingTagEnabled(string $key)Check if tag should be included$feature->isTracingTagEnabled('db.result')
isMetricsEnabled()Check if metrics collection is enabled$feature->isMetricsEnabled()
isCronsEnabled()Check if cron monitoring is enabled$feature->isCronsEnabled()

The feature flag checks short-circuit unnecessary instrumentation work when features are disabled:


Sources: src/sentry/src/Feature.php1-133 src/sentry/src/Tracing/Aspect/RedisConnectionAspect.php38-64


Hub and Client Initialization

The Sentry integration uses two factory classes to configure the SDK for Hyperf's architecture.

ClientBuilderFactory

The ClientBuilderFactory (src/sentry/src/Factory/ClientBuilderFactory.php1-76) creates a ClientBuilder instance with Hyperf-specific configuration:


Key initialization steps at src/sentry/src/Factory/ClientBuilderFactory.php32-74:

  1. Retrieve user configuration from ConfigInterface
  2. Filter configuration to valid Options keys using reflection
  3. Resolve logger instance if specified as container reference
  4. Set default prefixes and excludes for stack traces
  5. Resolve custom transport from container (CoHttpTransport)
  6. Set SDK identifier to friendsofhyperf.sentry with version

HubFactory

The HubFactory (src/sentry/src/Factory/HubFactory.php1-122) creates a Hub with custom integrations that replace default SDK integrations:


The factory removes default error listeners (src/sentry/src/Factory/HubFactory.php46-71) because Hyperf handles exceptions differently, then adds three custom integrations:

  • RequestFetcher: Extracts PSR-7 request from Hyperf context
  • ExceptionContextIntegration: Adds context() method data from exceptions
  • RequestIntegration: Sets user IP address for events

Sources: src/sentry/src/Factory/ClientBuilderFactory.php1-76 src/sentry/src/Factory/HubFactory.php1-122 src/sentry/src/Integration/RequestIntegration.php1-59 src/sentry/src/Integration/ExceptionContextIntegration.php1-46


AOP-Based Instrumentation

The component registers 28 aspects in ConfigProvider to transparently instrument method calls across the application.

Tracing Aspects


Server Address Tracking Pattern

Several aspects use a two-phase approach to track server addresses for spans:

Phase 1: Connection Establishment (src/sentry/src/Tracing/Aspect/DbConnectionAspect.php38-67)


Phase 2: Query Execution (src/sentry/src/Tracing/Aspect/DbConnectionAspect.php56-66)


This pattern separates connection tracking from query tracing, allowing the EventHandleListener to access server addresses via SentryContext when creating database spans.

Redis Cluster Support

The RedisConnectionAspect (src/sentry/src/Tracing/Aspect/RedisConnectionAspect.php38-86) handles both standalone Redis and RedisCluster:


The RedisClusterKeySlot::get() utility (src/sentry/src/Util/RedisClusterKeySlot.php51-68) calculates slot numbers using CRC16 to determine which cluster node handles a given key.

Distributed Tracing Injection

Several aspects inject trace headers into outgoing requests for distributed tracing:

gRPC Example (src/sentry/src/Tracing/Aspect/GrpcAspect.php66-73)


Sources: src/sentry/src/ConfigProvider.php21-51 src/sentry/src/Tracing/Aspect/DbConnectionAspect.php1-68 src/sentry/src/Tracing/Aspect/RedisConnectionAspect.php1-87 src/sentry/src/Tracing/Aspect/GrpcAspect.php1-84


Event-Driven Transaction Management

The EventHandleListener (src/sentry/src/Tracing/Listener/EventHandleListener.php1-754) is the primary component for creating Sentry transactions and spans. It listens to 30+ Hyperf events with priority PHP_INT_MAX to ensure it runs first.

Event to Handler Mapping


HTTP Request Transaction Flow

The request lifecycle creates a transaction with a nested span structure:

Request Received (src/sentry/src/Tracing/Listener/EventHandleListener.php267-341)


Database Query Span Creation

Database queries are recorded as spans under the current transaction:

Query Executed Handler (src/sentry/src/Tracing/Listener/EventHandleListener.php170-216)


Console Command Transaction Handling

Commands create a parent transaction and nested execution span:

Command Starting (src/sentry/src/Tracing/Listener/EventHandleListener.php366-416)


Command Finished (src/sentry/src/Tracing/Listener/EventHandleListener.php418-459)


Sources: src/sentry/src/Tracing/Listener/EventHandleListener.php1-754


Trace Context Propagation with Carrier

The Carrier utility ([referenced in src/sentry/src/Tracing/Listener/EventHandleListener.php:305,570,637]) serializes trace context for propagation across asynchronous boundaries.

Carrier Structure


AMQP Message Propagation

Producer Side (src/sentry/src/Tracing/Aspect/AmqpProducerAspect.php44-88 referenced in CHANGELOG)


Consumer Side (src/sentry/src/Tracing/Listener/EventHandleListener.php554-605)


AsyncQueue Job Propagation

Job Dispatch ([referenced in src/sentry/src/Tracing/Aspect/AsyncQueueJobMessageAspect.php via CHANGELOG])


Job Processing (src/sentry/src/Tracing/Listener/EventHandleListener.php685-717)


The carrier approach enables end-to-end distributed tracing across service boundaries and asynchronous processing, maintaining the causal relationship between operations.

Sources: src/sentry/src/Tracing/Listener/EventHandleListener.php305-717 CHANGELOG-3.1.md184


Coroutine Context Management

The SentryContext class (src/sentry/src/SentryContext.php1-161) provides a centralized API for storing tracing-related data in Hyperf's coroutine context.

Context Storage Keys

Context KeyPurposeSetterGetter
CTX_CRON_CHECKIN_IDCron job check-in ID for Sentry CronssetCronCheckInId()getCronCheckInId()
CTX_DISABLE_COROUTINE_TRACINGFlag to disable tracing in coroutinedisableTracing()isTracingDisabled()
CTX_CARRIERCarrier for trace propagationsetCarrier()getCarrier()
CTX_DB_SERVER_ADDRESSDatabase server hostsetDbServerAddress()getDbServerAddress()
CTX_DB_SERVER_PORTDatabase server portsetDbServerPort()getDbServerPort()
CTX_REDIS_SERVER_ADDRESSRedis server hostsetRedisServerAddress()getRedisServerAddress()
CTX_REDIS_SERVER_PORTRedis server portsetRedisServerPort()getRedisServerPort()
CTX_RPC_SERVER_ADDRESSRPC server hostsetRpcServerAddress()getRpcServerAddress()
CTX_RPC_SERVER_PORTRPC server portsetRpcServerPort()getRpcServerPort()
CTX_ELASTICSEARCH_SPAN_DATAElasticsearch request datasetElasticsearchSpanData()getElasticsearchSpanData()

Usage Pattern


The context isolation ensures that concurrent requests in different coroutines maintain separate server address tracking, preventing data contamination.

Trace Disabling

The disableTracing() and enableTracing() methods allow selective tracing suppression:


The Feature::isTracingSpanEnabled() method checks this flag before creating spans.

Sources: src/sentry/src/SentryContext.php1-161 src/sentry/src/Feature.php91-98


Metrics Collection System

The component includes a comprehensive metrics collection system for monitoring application resource usage.

Metrics Listeners


Default Metrics

The OnMetricFactoryReady listener (referenced in ConfigProvider.php69) collects system-level metrics:

  • Memory Usage: process.memory.usage and process.memory.real_usage
  • Process Count: process.count per worker

Pool Metrics

The DBPoolWatcher and RedisPoolWatcher track connection pool statistics:

  • Pool Size: db.pool.connections.usage / redis.pool.connections.usage
  • Idle Connections: db.pool.connections.idle / redis.pool.connections.idle
  • Pool Configuration: Tagged with pool.name, pool.max_connections, pool.max_idle_time

Queue Metrics

The QueueWatcher monitors async queue processing:

  • Waiting Jobs: Number of jobs pending execution
  • Failed Jobs: Count of failed job attempts
  • Tagged with queue name

Custom Metrics via Annotations

The component provides @Counter and @Histogram annotations for custom metrics (referenced in ConfigProvider.php31-32):


The CounterAspect and HistogramAspect intercept annotated methods to collect metrics.

Sources: src/sentry/publish/sentry.php66-70 src/sentry/src/ConfigProvider.php31-73 CHANGELOG-3.1.md53-55


Cron Job Monitoring

The Crons\Listener\EventHandleListener (src/sentry/src/Crons/Listener/EventHandleListener.php1-155) integrates with Sentry Crons for cron job monitoring and alerting.

Check-In Lifecycle


Monitor Configuration

The createMonitorConfig() method (src/sentry/src/Crons/Listener/EventHandleListener.php131-154) builds a MonitorConfig with:

ParameterSourceDefault
scheduleCrontab rule (e.g., * * * * *)Required
checkinMarginConfig or crontab options5 minutes
maxRuntimeConfig or crontab options15 minutes
timezoneCrontab timezone or configSystem timezone
failureIssueThresholdCrontab optionsnull
recoveryThresholdCrontab optionsnull

Crontab Options

Cron jobs can be configured with monitoring options:


Setting options.monitor = false disables monitoring for specific jobs.

Sources: src/sentry/src/Crons/Listener/EventHandleListener.php1-155 src/sentry/publish/sentry.php173-179


Global Functions API

The component provides convenience functions in the FriendsOfHyperf\Sentry namespace for manual instrumentation.

Transaction Management


Usage Example


These functions integrate with the per-coroutine Hub management to maintain proper span hierarchy.

Sources: src/sentry/src/Tracing/Listener/EventHandleListener.php55-56


Transport Implementation

The CoHttpTransport class (referenced in src/sentry/src/ConfigProvider.php60) replaces Sentry's default Guzzle-based transport with a Swoole coroutine-compatible HTTP client.

Transport Configuration

The transport uses channels for non-blocking event submission:

Configuration KeyEnvironment VariableDefaultPurpose
transport_channel_sizeSENTRY_TRANSPORT_CHANNEL_SIZE65535Channel buffer size
transport_concurrent_limitSENTRY_TRANSPORT_CONCURRENT_LIMIT1000Max concurrent requests
http_timeoutSENTRY_HTTP_TIMEOUT2.0HTTP request timeout (seconds)

The transport queues events in a channel and processes them asynchronously, preventing blocking of the main application flow during Sentry API communication.

Sources: src/sentry/publish/sentry.php181-186 src/sentry/src/ConfigProvider.php60


Integration Summary Table

Integration PointImplementationConfiguration KeyPurpose
HTTP RequestsEventHandleListener::handleRequestReceived()enable.request, tracing.requestCreate transactions for HTTP requests
Console CommandsEventHandleListener::handleCommandStarting()enable.command, tracing.commandCreate transactions for CLI commands
Cron JobsEventHandleListener::handleCrontabTaskStarting()enable.crontab, tracing.crontabCreate transactions for scheduled tasks
Cron MonitoringCrons\EventHandleListenercrons.enableSend check-ins to Sentry Crons
Database QueriesEventHandleListener::handleDbQueryExecuted()tracing_spans.dbCreate spans for SQL queries
Redis CommandsEventHandleListener::handleRedisCommandExecuted()tracing_spans.redisCreate spans for Redis operations
HTTP ClientGuzzleHttpClientAspecttracing_spans.guzzleCreate spans for outgoing HTTP requests
RPC CallsRpcAspecttracing_spans.rpcCreate spans for RPC method calls
gRPC CallsGrpcAspecttracing_spans.grpcCreate spans for gRPC requests
ElasticsearchElasticsearchAspecttracing_spans.elasticsearchCreate spans for search queries
Cache OperationsCacheAspecttracing_spans.cacheCreate spans for cache access
FilesystemFilesystemAspecttracing_spans.filesystemCreate spans for file operations
View RenderingViewRenderAspecttracing_spans.viewCreate spans for template rendering
AsyncQueue JobsEventHandleListener::handleAsyncQueueJobProcessing()enable.async_queue, tracing.async_queueCreate transactions for queued jobs
AMQP MessagesEventHandleListener::handleAmqpMessageProcessing()enable.amqp, tracing.amqpCreate transactions for message consumers
Kafka MessagesEventHandleListener::handleKafkaMessageProcessing()enable.kafka, tracing.kafkaCreate transactions for Kafka consumers
BreadcrumbsBreadcrumbAspectbreadcrumbs.*Capture contextual data for errors
MetricsVarious *Watcher listenersenable_metricsCollect system and pool metrics

Sources: src/sentry/src/ConfigProvider.php1-93 src/sentry/publish/sentry.php96-159

Refresh this wiki

On this page