{"id":15137096,"url":"https://github.com/overtrue/laravel-open-telemetry","last_synced_at":"2025-10-23T12:30:26.687Z","repository":{"id":235703021,"uuid":"787916424","full_name":"overtrue/laravel-open-telemetry","owner":"overtrue","description":"This package provides a simple way to add OpenTelemetry to your Laravel application.","archived":false,"fork":false,"pushed_at":"2024-06-19T08:02:35.000Z","size":150,"stargazers_count":11,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-30T18:47:47.606Z","etag":null,"topics":["laravel-package","opentelemetry","opentelemetry-laravel","opentelemetry-php","opentracing","tracing-library"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/overtrue.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["overtrue"],"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"lfx_crowdfunding":null,"polar":null,"buy_me_a_coffee":null,"custom":null}},"created_at":"2024-04-17T12:32:13.000Z","updated_at":"2024-06-19T08:02:38.000Z","dependencies_parsed_at":"2024-05-29T10:58:17.929Z","dependency_job_id":"45c7a9f8-b727-4ebf-9503-c259c78ed161","html_url":"https://github.com/overtrue/laravel-open-telemetry","commit_stats":null,"previous_names":["overtrue/laravel-open-telemetry"],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/overtrue%2Flaravel-open-telemetry","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/overtrue%2Flaravel-open-telemetry/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/overtrue%2Flaravel-open-telemetry/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/overtrue%2Flaravel-open-telemetry/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/overtrue","download_url":"https://codeload.github.com/overtrue/laravel-open-telemetry/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":237821786,"owners_count":19371827,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["laravel-package","opentelemetry","opentelemetry-laravel","opentelemetry-php","opentracing","tracing-library"],"created_at":"2024-09-26T07:00:19.764Z","updated_at":"2025-10-23T12:30:26.681Z","avatar_url":"https://github.com/overtrue.png","language":"PHP","funding_links":["https://github.com/sponsors/overtrue"],"categories":[],"sub_categories":[],"readme":"# Laravel OpenTelemetry\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/overtrue/laravel-open-telemetry.svg?style=flat-square)](https://packagist.org/packages/overtrue/laravel-open-telemetry)\n[![Total Downloads](https://img.shields.io/packagist/dt/overtrue/laravel-open-telemetry.svg?style=flat-square)](https://packagist.org/packages/overtrue/laravel-open-telemetry)\n\nThis package provides a simple way to add OpenTelemetry to your Laravel application.\n\n## Features\n\n- ✅ **Zero Configuration**: Works out of the box with sensible defaults.\n- ✅ **Laravel Native**: Deep integration with Laravel's lifecycle and events.\n- ✅ **Octane \u0026 FPM Support**: Full compatibility with Laravel Octane and traditional FPM setups.\n- ✅ **Powerful `Measure` Facade**: Provides an elegant API for manual, semantic tracing.\n- ✅ **Automatic Tracing**: Built-in watchers for cache, database, HTTP clients, queues, and more.\n- ✅ **Flexible Configuration**: Control traced paths, headers, and watchers to fit your needs.\n- ✅ **Standards Compliant**: Adheres to OpenTelemetry Semantic Conventions.\n\n## Installation\n\nYou can install the package via composer:\n\n```bash\ncomposer require overtrue/laravel-open-telemetry\n```\n\n## Configuration\n\n\u003e **Important Note for Octane Users**\n\u003e\n\u003e When using Laravel Octane, it is **highly recommended** to set `OTEL_*` environment variables at the machine or process level (e.g., in your Dockerfile, `docker-compose.yml`, or Supervisor configuration) rather than relying solely on the `.env` file.\n\u003e\n\u003e This is because some OpenTelemetry components, especially those enabled by `OTEL_PHP_AUTOLOAD_ENABLED`, are initialized before the Laravel application fully boots and reads the `.env` file. Setting them as system-level environment variables ensures they are available to the PHP process from the very beginning.\n\nThis package uses the standard OpenTelemetry environment variables for configuration. Add these to your `.env` file for basic setup:\n\n### Basic Configuration\n\n```env\n# Enable OpenTelemetry PHP SDK auto-loading\nOTEL_PHP_AUTOLOAD_ENABLED=true\n\n# Service identification\nOTEL_SERVICE_NAME=my-laravel-app\nOTEL_SERVICE_VERSION=1.0.0\n\n# Exporter configuration (console for dev, otlp for prod)\nOTEL_TRACES_EXPORTER=console\nOTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318\nOTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf\n\n# Context propagation\nOTEL_PROPAGATORS=tracecontext,baggage\n```\n\n### Package Configuration\n\nFor package-specific settings, publish the configuration file:\n\n```bash\nphp artisan vendor:publish --provider=\"Overtrue\\LaravelOpenTelemetry\\OpenTelemetryServiceProvider\" --tag=config\n```\n\nThis will create a `config/otel.php` file. Here are the key options:\n\n#### Enabling/Disabling Tracing\n\nYou can completely enable or disable tracing for the entire application. This is useful for performance tuning or disabling tracing in certain environments.\n\n```php\n// config/otel.php\n'enabled' =\u003e env('OTEL_ENABLED', true),\n```\nSet `OTEL_ENABLED=false` in your `.env` file to disable all tracing.\n\n**Log Format**: All OpenTelemetry logs are prefixed with `[laravel-open-telemetry]` for easy identification and filtering.\n\n#### Filtering Requests and Headers\n\nYou can control which requests are traced and which headers are recorded to enhance performance and protect sensitive data. All patterns support wildcards (`*`) and are case-insensitive.\n\n- **`ignore_paths`**: A list of request paths to exclude from tracing. Useful for health checks, metrics endpoints, etc.\n  ```php\n  'ignore_paths' =\u003e ['health*', 'telescope*', 'horizon*'],\n  ```\n- **`allowed_headers`**: A list of HTTP header patterns to include in spans. If empty, no headers are recorded.\n  ```php\n  'allowed_headers' =\u003e ['x-request-id', 'user-agent', 'authorization'],\n  ```\n- **`sensitive_headers`**: A list of header patterns whose values will be masked (replaced with `***`).\n  ```php\n  'sensitive_headers' =\u003e ['authorization', 'cookie', 'x-api-key', '*-token'],\n  ```\n\n#### Watchers\n\nYou can enable or disable specific watchers to trace different parts of your application.\n\n```php\n// config/otel.php\n'watchers' =\u003e [\n    \\Overtrue\\LaravelOpenTelemetry\\Watchers\\CacheWatcher::class =\u003e env('OTEL_CACHE_WATCHER_ENABLED', true),\n    \\Overtrue\\LaravelOpenTelemetry\\Watchers\\QueryWatcher::class =\u003e env('OTEL_QUERY_WATCHER_ENABLED', true),\n    // ...\n],\n```\n\n## Usage\n\nThe package is designed to work with minimal manual intervention, but it also provides a powerful `Measure` facade for creating custom spans.\n\n### Automatic Tracing\n\nWith the default configuration, the package automatically traces:\n- Incoming HTTP requests.\n- Database queries (`QueryWatcher`).\n- Cache operations (`CacheWatcher`).\n- Outgoing HTTP client requests (`HttpClientWatcher`).\n- Thrown exceptions (`ExceptionWatcher`).\n- Queue jobs (`QueueWatcher`).\n- ...and more, depending on the enabled [watchers](#watchers).\n\n### Creating Custom Spans with `Measure::trace()`\n\nFor tracing specific blocks of code, the `Measure::trace()` method is the recommended approach. It automatically handles span creation, activation, exception recording, and completion.\n\n```php\nuse Overtrue\\LaravelOpenTelemetry\\Facades\\Measure;\n\nMeasure::trace('process-user-data', function ($span) use ($user) {\n    // Add attributes to the span\n    $span-\u003esetAttribute('user.id', $user-\u003eid);\n\n    // Your business logic here\n    $this-\u003eprocess($user);\n\n    // Add an event to mark a point in time within the span\n    $span-\u003eaddEvent('User processing finished');\n});\n```\n\nThe `trace` method will:\n- Start a new span.\n- Execute the callback.\n- Automatically record and re-throw any exceptions that occur within the callback.\n- End the span when the callback completes.\n\n### Advanced Span Creation with SpanBuilder\n\nFor more control over span lifecycle, you can use the `SpanBuilder` directly through `Measure::span()`. The SpanBuilder provides several methods for different use cases:\n\n#### Basic Span Creation (Recommended for most cases)\n\n```php\n// Create a span without activating its scope (safer for async operations)\n$span = Measure::span('my-operation')\n    -\u003esetAttribute('operation.type', 'data-processing')\n    -\u003esetSpanKind(SpanKind::KIND_INTERNAL)\n    -\u003estart(); // Returns SpanInterface\n\n// Your business logic here\n$result = $this-\u003eprocessData();\n\n// Remember to end the span manually\n$span-\u003eend();\n```\n\n#### Span with Activated Scope\n\n```php\n// Create a span and activate its scope (for nested operations)\n$startedSpan = Measure::span('parent-operation')\n    -\u003esetAttribute('operation.type', 'user-workflow')\n    -\u003esetSpanKind(SpanKind::KIND_INTERNAL)\n    -\u003estartAndActivate(); // Returns StartedSpan\n\n// Any spans created within this block will be children of this span\n$childSpan = Measure::span('child-operation')-\u003estart();\n$childSpan-\u003eend();\n\n// The StartedSpan automatically manages scope cleanup\n$startedSpan-\u003eend(); // Ends span and detaches scope\n```\n\n#### Span with Context (For Manual Propagation)\n\n```php\n// Create a span and get both span and context for manual management\n[$span, $context] = Measure::span('async-operation')\n    -\u003esetAttribute('operation.async', true)\n    -\u003estartWithContext(); // Returns [SpanInterface, ContextInterface]\n\n// Use context for propagation (e.g., in HTTP headers)\n$headers = Measure::propagationHeaders($context);\n\n// Your async operation here\n$span-\u003eend();\n```\n\n### Using Semantic Spans\n\nTo promote standardization, the package provides semantic helper methods that create spans with attributes conforming to OpenTelemetry's [Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/).\n\n#### Database Spans\n```php\n// Manually trace a block of database operations\n$user = Measure::database('SELECT', 'users'); // Quick shortcut for database operations\n// Or use the general trace method for more complex operations\n$user = Measure::trace('repository:find-user', function ($span) use ($userId) {\n    $span-\u003esetAttribute('db.statement', \"SELECT * FROM users WHERE id = ?\");\n    $span-\u003esetAttribute('db.table', 'users');\n    return User::find($userId);\n});\n```\n*Note: If `QueryWatcher` is enabled, individual queries are already traced. This is useful for tracing a larger transaction or a specific business operation involving multiple queries.*\n\n#### HTTP Client Spans\n```php\n// Quick shortcut for HTTP client requests\n$response = Measure::httpClient('POST', 'https://api.example.com/users');\n// Or use the general trace method for more control\n$response = Measure::trace('api-call', function ($span) {\n    $span-\u003esetAttribute('http.method', 'POST');\n    $span-\u003esetAttribute('http.url', 'https://api.example.com/users');\n    return Http::post('https://api.example.com/users', $data);\n});\n```\n\n#### Custom Spans\n```php\n// For any custom operation, use the general trace method\n$result = Measure::trace('process-payment', function ($span) use ($payment) {\n    $span-\u003esetAttribute('payment.amount', $payment-\u003eamount);\n    $span-\u003esetAttribute('payment.currency', $payment-\u003ecurrency);\n\n    // Your business logic here\n    return $this-\u003eprocessPayment($payment);\n});\n```\n\n### Retrieving the Current Span\n\nYou can access the currently active span anywhere in your code.\n\n```php\nuse Overtrue\\LaravelOpenTelemetry\\Facades\\Measure;\n\n$currentSpan = Measure::activeSpan();\n$currentSpan-\u003esetAttribute('custom.attribute', 'some_value');\n```\n\n### Watchers\n\nThe package includes several watchers that automatically create spans for common Laravel operations. You can enable or disable them in `config/otel.php`.\n\n- **`CacheWatcher`**: Traces cache hits, misses, writes, and forgets.\n- **`QueryWatcher`**: Traces the execution of every database query.\n- **`HttpClientWatcher`**: Traces all outgoing HTTP requests made with Laravel's `Http` facade.\n- **`ExceptionWatcher`**: Traces all exceptions thrown in your application.\n- **`QueueWatcher`**: Traces jobs being dispatched, processed, and failing.\n- **`RedisWatcher`**: Traces Redis commands.\n- **`AuthenticateWatcher`**: Traces authentication events like login, logout, and failed attempts.\n\n\n### Trace ID Injection Middleware\n\nThe package includes middleware to add a `X-Trace-Id` header to your HTTP responses, which is useful for debugging.\n\nYou can apply it to specific routes:\n```php\n// In your routes/web.php or routes/api.php\nRoute::middleware('otel.traceid')-\u003egroup(function () {\n    Route::get('/api/users', [UserController::class, 'index']);\n});\n```\n\nOr apply it globally in `app/Http/Kernel.php`:\n```php\n// app/Http/Kernel.php\n\n// In the $middlewareGroups property for 'web' or 'api'\nprotected $middlewareGroups = [\n    'web' =\u003e [\n        // ...\n        \\Overtrue\\LaravelOpenTelemetry\\Http\\Middleware\\AddTraceId::class,\n    ],\n    // ...\n];\n```\n\n## Environment Variables Reference\n\n### Core OpenTelemetry Variables\n\n| Variable | Description | Default | Example |\n|----------|-------------|---------|---------|\n| `OTEL_PHP_AUTOLOAD_ENABLED` | Enable PHP SDK auto-loading | `false` | `true` |\n| `OTEL_SERVICE_NAME` | Service name | `unknown_service` | `my-laravel-app` |\n| `OTEL_SERVICE_VERSION` | Service version | `null` | `1.0.0` |\n| `OTEL_TRACES_EXPORTER` | Trace exporter type | `otlp` | `console`, `otlp` |\n| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP endpoint URL | `http://localhost:4318` | `https://api.honeycomb.io` |\n| `OTEL_EXPORTER_OTLP_PROTOCOL` | OTLP protocol | `http/protobuf` | `http/protobuf`, `grpc` |\n| `OTEL_PROPAGATORS` | Context propagators | `tracecontext,baggage` | `tracecontext,baggage,b3` |\n| `OTEL_TRACES_SAMPLER` | Sampling strategy | `parentbased_always_on` | `always_on`, `traceidratio` |\n| `OTEL_TRACES_SAMPLER_ARG` | Sampler argument | `null` | `0.1` |\n| `OTEL_RESOURCE_ATTRIBUTES` | Resource attributes | `null` | `key1=value1,key2=value2` |\n\n## Testing\n\n```bash\ncomposer test\n```\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](CONTRIBUTING.md) for details.\n\n## Security Vulnerabilities\n\nPlease review [our security policy](../../security/policy) on how to report security vulnerabilities.\n\n## Credits\n\n- [overtrue](https://github.com/overtrue)\n- [All Contributors](../../contributors)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fovertrue%2Flaravel-open-telemetry","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fovertrue%2Flaravel-open-telemetry","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fovertrue%2Flaravel-open-telemetry/lists"}