Skip to content

Observability Packages

Observability packages provide comprehensive monitoring, tracing, and error tracking capabilities.

OpenTelemetry-based distributed tracing for application performance monitoring.

  • HTTP request tracing
  • Database query monitoring
  • Cache/Redis operation tracking
  • Queue job tracing
  • Attribute-based method decoration

LaravelApmServiceProvider registers the tracer and tracking components.

use RightCapital\LaravelApm\ApmTracer;
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
}
}
// Run code in a span
ApmTracer::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();
TraitMonitors
TracksDatabaseTraitSQL queries, execution time
TracksRequestTraitHTTP request/response
TracksCacheTraitCache operations
TracksRedisTraitRedis commands
TracksQueueTraitQueue job processing
config/apm.php
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,
];
  • open-telemetry/sdk, open-telemetry/exporter-otlp
  • open-telemetry/transport-grpc
  • rightcapital/method-delegate

Enhanced error tracking with context collection and exception integrations.

  • Exception and error capture
  • Custom context and tags
  • Breadcrumb tracking
  • Sensitive field masking
  • First-party exception interface
use RightCapital\LaravelSentry\LaravelSentry;
// Capture message
LaravelSentry::captureMessage(
'My message',
\Sentry\Severity::debug(),
['extra_data' => 'value'],
['tags' => ['color' => 'blue']]
);
// Capture exception
LaravelSentry::captureException(
$throwable,
\Sentry\Severity::error(),
['context' => 'data'],
['tags' => ['type' => 'critical']]
);
// Add breadcrumb
LaravelSentry::addBreadcrumb(
'category',
'Something happened',
['data' => 'value']
);
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';
}
}
IntegrationPurpose
AuthIntegrationCaptures authenticated user info
RequestIntegrationCaptures request/response data
SentryExceptionIntegrationFirst-party exception handling
GuzzleRequestExceptionIntegrationGuzzle HTTP errors
IlluminateValidationExceptionIntegrationValidation errors
SymfonyHttpExceptionIntegrationHTTP exceptions
config/sentry.php
'integrations' => [
AuthIntegration::class,
SentryExceptionIntegration::class,
GuzzleRequestExceptionIntegration::class,
IlluminateValidationExceptionIntegration::class,
],
// config/sentry-laravel.php
'sanitization' => [
'cookie_patterns' => ['string'],
'header_patterns' => ['/^regex/'],
'request_body_patterns' => ['/regex$/'],
],

Job health monitoring with Cronitor integration.

  • Scheduled job status tracking
  • Multi-pod execution tracking (Kubernetes)
  • Configurable ping states

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',
]);
config/services.php
'cronitor' => [
'api_key' => env('CRONITOR_API_KEY'),
'monitor_key' => env('CRONITOR_MONITOR_KEY'),
'series' => env('CRONITOR_SERIES'), // Pod identifier
],

N+1 query detection with Sentry reporting and test thresholds.

  • N+1 query pattern detection
  • Sentry reporting for production
  • Test query count thresholds
  • Console output for development
ClassEnvironmentAction
SentryOutputProductionReports to Sentry as warning
TestingOutputTestingEnforces query count thresholds
// Automatic message format:
"Potential n+1 query detected on ModelName.relationshipName in route.name"
// Includes context:
// - model, relation, count
// - query, time, call-stack
Terminal window
# Environment variable
TOLERABLE_QUERY_COUNT=150
# Output format (colored):
# - Blue: "Detected N+1 Query"
# - Red: "Over tolerable" queries
# - Suggested optimal threshold

Add outputs to beyondcode/laravel-query-detector:

'outputs' => [
SentryOutput::class,
TestingOutput::class,
],

Structured file logging with multiple format support.

  • JSON, CSV, TXT, XML formats
  • Automatic object serialization
  • Sensitive field masking
  • Sequence numbering
  • Retention-based purging
use RightCapital\FileLog\FileLog;
// Configure
FileLog::setLocation('/tmp/logs');
FileLog::registerMetaProvider(fn($meta) =>
array_merge($meta, ['service' => 'api'])
);
// Log data
FileLog::write(
['project', 'subfolder'], // Path
'audit', // Filename prefix
$variable // Data
);
// Log as CSV
FileLog::write(['project'], 'data', $array, Extension::CSV);
// Purge old logs
FileLog::purge(['project'], days: 30);
FormatSupportsLimitations
JSONComplex structuresNone
CSV1D/2D arraysTypes lost
TXTSingle string, 1D arraysItems newline-separated
XMLStructured dataVia XML parser

authorization, auth, password, passwd, secret, card_number, credentials, token, key, apikey

  • Laravel Collections and Eloquent models
  • Guzzle HTTP Request/Response
  • Carbon dates
  • PHP enums
  • Closures, Resources (converted to strings)
config/file-log.php
return [
'location' => env('FILE_LOG_LOCATION', 'temp/logs'),
'disk' => env('FILE_LOG_DISK', 'local'),
];

┌─────────────────────────────────────────┐
│ 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) │
└─────────────────────────────────────────┘
PackageTypePurposeExternal Service
laravel-apmTracingPerformance monitoringOpenTelemetry
laravel-sentryError trackingException reportingSentry
laravel-cronitorHealth checkJob monitoringCronitor
laravel-query-detector-outputsQuery analysisN+1 detectionSentry
file-logLoggingStructured file logsFilesystem