Observability Packages
Observability packages provide comprehensive monitoring, tracing, and error tracking capabilities.
laravel-apm
Section titled “laravel-apm”OpenTelemetry-based distributed tracing for application performance monitoring.
Key Features
Section titled “Key Features”- HTTP request tracing
- Database query monitoring
- Cache/Redis operation tracking
- Queue job tracing
- Attribute-based method decoration
Service Provider
Section titled “Service Provider”LaravelApmServiceProvider registers the tracer and tracking components.
Facade
Section titled “Facade”use RightCapital\LaravelApm\ApmTracer;Attribute-Based Tracing
Section titled “Attribute-Based Tracing”use RightCapital\LaravelApm\Delegate\Apm;use OpenTelemetry\API\Trace\SpanKind;use OpenTelemetry\SemConv\TraceAttributes;
class CalculationService { #[Apm( kind: SpanKind::KIND_CLIENT, attributes: [TraceAttributes::PEER_SERVICE => 'calc-api'] )] public function calculate(): float { // Automatically traced }}Manual Span Tracking
Section titled “Manual Span Tracking”// Run code in a spanApmTracer::runInSpan( function (SpanInterface $span) { $span->addEvent('Processing started'); $span->setAttribute('custom_key', 'value'); // ... work }, 'span_name', ['attribute' => 'value'], SpanKind::KIND_INTERNAL);
// Direct span builder$span = ApmTracer::spanBuilder('CUSTOM_NAME')->startSpan();$scope = $span->activate();// ... work$span->end();$scope->detach();Tracking Traits
Section titled “Tracking Traits”| Trait | Monitors |
|---|---|
TracksDatabaseTrait | SQL queries, execution time |
TracksRequestTrait | HTTP request/response |
TracksCacheTrait | Cache operations |
TracksRedisTrait | Redis commands |
TracksQueueTrait | Queue job processing |
Configuration
Section titled “Configuration”return [ 'enabled' => env('OPEN_TELEMETRY_ENABLED', true), 'endpoint' => env('OPEN_TELEMETRY_OTLP_ENDPOINT', 'opentelemetry-collector.opentelemetry-collector.svc:4317'), 'exclude_uri_prefixes' => [], 'preference_handler' => DefaultPreference::class,];Dependencies
Section titled “Dependencies”open-telemetry/sdk,open-telemetry/exporter-otlpopen-telemetry/transport-grpcrightcapital/method-delegate
laravel-sentry
Section titled “laravel-sentry”Enhanced error tracking with context collection and exception integrations.
Key Features
Section titled “Key Features”- Exception and error capture
- Custom context and tags
- Breadcrumb tracking
- Sensitive field masking
- First-party exception interface
use RightCapital\LaravelSentry\LaravelSentry;
// Capture messageLaravelSentry::captureMessage( 'My message', \Sentry\Severity::debug(), ['extra_data' => 'value'], ['tags' => ['color' => 'blue']]);
// Capture exceptionLaravelSentry::captureException( $throwable, \Sentry\Severity::error(), ['context' => 'data'], ['tags' => ['type' => 'critical']]);
// Add breadcrumbLaravelSentry::addBreadcrumb( 'category', 'Something happened', ['data' => 'value']);First-Party Exceptions
Section titled “First-Party Exceptions”use RightCapital\LaravelSentry\SentryExceptionInterface;
class MyException extends \Exception implements SentryExceptionInterface { public function getSentryErrorLevel(): ?string { return 'error'; }
public function getSentryExtraData(): array { return ['context' => $this->context]; }
public function getSentryTags(): array { return ['type' => 'custom']; }
public function getSentryLogger(): ?string { return 'custom_logger'; }}Integrations
Section titled “Integrations”| Integration | Purpose |
|---|---|
AuthIntegration | Captures authenticated user info |
RequestIntegration | Captures request/response data |
SentryExceptionIntegration | First-party exception handling |
GuzzleRequestExceptionIntegration | Guzzle HTTP errors |
IlluminateValidationExceptionIntegration | Validation errors |
SymfonyHttpExceptionIntegration | HTTP exceptions |
Configuration
Section titled “Configuration”'integrations' => [ AuthIntegration::class, SentryExceptionIntegration::class, GuzzleRequestExceptionIntegration::class, IlluminateValidationExceptionIntegration::class,],
// config/sentry-laravel.php'sanitization' => [ 'cookie_patterns' => ['string'], 'header_patterns' => ['/^regex/'], 'request_body_patterns' => ['/regex$/'],],laravel-cronitor
Section titled “laravel-cronitor”Job health monitoring with Cronitor integration.
Key Features
Section titled “Key Features”- Scheduled job status tracking
- Multi-pod execution tracking (Kubernetes)
- Configurable ping states
Service Provider
Section titled “Service Provider”CronitorServiceProvider registers the client.
$monitor = resolve('cronitor');
// Job started$monitor->ping(['state' => 'run']);
// Job completed$monitor->ping(['state' => 'complete']);
// Job failed$monitor->ping([ 'state' => 'fail', 'output' => 'Error message', 'series' => 'pod-identifier',]);Configuration
Section titled “Configuration”'cronitor' => [ 'api_key' => env('CRONITOR_API_KEY'), 'monitor_key' => env('CRONITOR_MONITOR_KEY'), 'series' => env('CRONITOR_SERIES'), // Pod identifier],laravel-query-detector-outputs
Section titled “laravel-query-detector-outputs”N+1 query detection with Sentry reporting and test thresholds.
Key Features
Section titled “Key Features”- N+1 query pattern detection
- Sentry reporting for production
- Test query count thresholds
- Console output for development
Output Classes
Section titled “Output Classes”| Class | Environment | Action |
|---|---|---|
SentryOutput | Production | Reports to Sentry as warning |
TestingOutput | Testing | Enforces query count thresholds |
Sentry Output
Section titled “Sentry Output”// Automatic message format:"Potential n+1 query detected on ModelName.relationshipName in route.name"
// Includes context:// - model, relation, count// - query, time, call-stackTesting Output
Section titled “Testing Output”# Environment variableTOLERABLE_QUERY_COUNT=150
# Output format (colored):# - Blue: "Detected N+1 Query"# - Red: "Over tolerable" queries# - Suggested optimal thresholdConfiguration
Section titled “Configuration”Add outputs to beyondcode/laravel-query-detector:
'outputs' => [ SentryOutput::class, TestingOutput::class,],file-log
Section titled “file-log”Structured file logging with multiple format support.
Key Features
Section titled “Key Features”- JSON, CSV, TXT, XML formats
- Automatic object serialization
- Sensitive field masking
- Sequence numbering
- Retention-based purging
use RightCapital\FileLog\FileLog;
// ConfigureFileLog::setLocation('/tmp/logs');FileLog::registerMetaProvider(fn($meta) => array_merge($meta, ['service' => 'api']));
// Log dataFileLog::write( ['project', 'subfolder'], // Path 'audit', // Filename prefix $variable // Data);
// Log as CSVFileLog::write(['project'], 'data', $array, Extension::CSV);
// Purge old logsFileLog::purge(['project'], days: 30);Output Formats
Section titled “Output Formats”| Format | Supports | Limitations |
|---|---|---|
| JSON | Complex structures | None |
| CSV | 1D/2D arrays | Types lost |
| TXT | Single string, 1D arrays | Items newline-separated |
| XML | Structured data | Via XML parser |
Sensitive Fields (Auto-Masked)
Section titled “Sensitive Fields (Auto-Masked)”authorization, auth, password, passwd, secret, card_number, credentials, token, key, apikey
Supported Object Types
Section titled “Supported Object Types”- Laravel Collections and Eloquent models
- Guzzle HTTP Request/Response
- Carbon dates
- PHP enums
- Closures, Resources (converted to strings)
Configuration
Section titled “Configuration”return [ 'location' => env('FILE_LOG_LOCATION', 'temp/logs'), 'disk' => env('FILE_LOG_DISK', 'local'),];Architecture Overview
Section titled “Architecture Overview”┌─────────────────────────────────────────┐│ Request/Job Processing │└─────────────────────────────────────────┘ │ ┌───────────┴───────────┐ ▼ ▼┌───────────────┐ ┌───────────────┐│ Laravel APM │ │ Laravel Sentry││ │ │ ││ • HTTP traces │ │ • Exceptions ││ • DB queries │ │ • Errors ││ • Cache ops │ │ • Validation ││ • Queue jobs │ │ • Context │└───────────────┘ └───────────────┘ │ │ ▼ ▼┌───────────────┐ ┌───────────────┐│ OpenTelemetry│ │ Sentry ││ Collector │ │ Service │└───────────────┘ └───────────────┘
┌─────────────────────────────────────────┐│ Query Detection (N+1) │├─────────────────────────────────────────┤│ SentryOutput (Prod) → Sentry ││ TestingOutput (Test) → Console + Error │└─────────────────────────────────────────┘
┌─────────────────────────────────────────┐│ Background Job Monitoring │├─────────────────────────────────────────┤│ Laravel Cronitor → Cronitor API │└─────────────────────────────────────────┘
┌─────────────────────────────────────────┐│ Debug/Data Export │├─────────────────────────────────────────┤│ File Log → Filesystem (JSON/CSV/TXT) │└─────────────────────────────────────────┘Summary
Section titled “Summary”| Package | Type | Purpose | External Service |
|---|---|---|---|
| laravel-apm | Tracing | Performance monitoring | OpenTelemetry |
| laravel-sentry | Error tracking | Exception reporting | Sentry |
| laravel-cronitor | Health check | Job monitoring | Cronitor |
| laravel-query-detector-outputs | Query analysis | N+1 detection | Sentry |
| file-log | Logging | Structured file logs | Filesystem |