Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Api Laravel Package

open-telemetry/api

OpenTelemetry PHP API package: vendor-neutral interfaces and context propagation for traces, metrics, and logs. Use it to instrument libraries/apps while staying decoupled from any specific SDK implementation. Documentation at opentelemetry.io.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require open-telemetry/api
    

    (Note: This is a pure API package—you’ll need an SDK like open-telemetry/sdk for actual instrumentation.)

  2. First use case: Instrument a route with tracing

    use OpenTelemetry\API\Common\Instrumentation\SpanKind;
    use OpenTelemetry\API\Trace\Span;
    use OpenTelemetry\API\Trace\TracerInterface;
    
    // In your Laravel service provider or route closure:
    $tracer = \OpenTelemetry\API\GlobalTracer::getTracer('my-app');
    $span = $tracer->spanBuilder('process-request')
        ->setSpanKind(SpanKind::SPAN_KIND_SERVER)
        ->startSpan();
    
    try {
        // Your route logic here
        $span->addEvent('request-processed');
    } finally {
        $span->end();
    }
    
  3. Key entry points:

    • GlobalTracer::getTracer() → For trace instrumentation.
    • GlobalMeter::getMeter() → For metrics.
    • GlobalPropagator::getTextMapPropagator() → For context propagation.
  4. Where to look first:


Implementation Patterns

1. Tracing Workflows

Automatic Instrumentation (Laravel-Specific)

Use the open-telemetry/auto-instrumentation package to auto-instrument HTTP requests, database queries, and queues:

// In `AppServiceProvider`:
\OpenTelemetry\AutoInstrumentation\AutoInstrumentation::register(
    \OpenTelemetry\AutoInstrumentation\Instrumentation\LaravelInstrumentation::class
);

Manual Span Management

// Wrap business logic in spans:
$span = $tracer->spanBuilder('user-authentication')
    ->setAttribute('user.id', $userId)
    ->startSpan();

try {
    $authService->authenticate($credentials);
    $span->setStatus(Span::STATUS_OK);
} catch (Exception $e) {
    $span->recordException($e);
    $span->setStatus(Span::STATUS_ERROR, 'Authentication failed');
} finally {
    $span->end();
}

Context Propagation (HTTP)

Inject context into outgoing requests and extract from incoming:

// Incoming request (e.g., middleware):
$propagator = \OpenTelemetry\API\GlobalPropagator::getTextMapPropagator();
$context = $propagator->extract(
    \OpenTelemetry\Context\Context::getCurrent(),
    $_SERVER
);

// Outgoing request (e.g., HTTP client):
$propagator->inject($context, $headers);

2. Metrics Workflows

Counter Example

$meter = \OpenTelemetry\API\GlobalMeter::getMeter('my-app');
$counter = $meter->getInt64Counter('api.requests');
$counter->add(1, ['method' => 'GET', 'endpoint' => '/users']);

Histogram for Latency

$histogram = $meter->getHistogram('request.latency.ms');
$histogram->record($executionTimeMs, ['endpoint' => '/users']);

Observer for Custom Logic

$meter->getObservableGauge('cache.hits')->addCallback(
    function (callable $observer) {
        $observer($this->getCacheHits());
    }
);

3. Integration with Laravel

Service Provider Setup

// config/app.php
'providers' => [
    // ...
    OpenTelemetry\SDK\Laravel\OpenTelemetryServiceProvider::class,
];

// .env
OTEL_SERVICE_NAME=my-laravel-app
OTEL_TRACES_EXPORTER=otlp
OTEL_METRICS_EXPORTER=otlp
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317

Middleware for Auto-Tracing

// app/Http/Middleware/TraceRequests.php
public function handle($request, Closure $next) {
    $span = \OpenTelemetry\API\GlobalTracer::getTracer('laravel')
        ->spanBuilder('http.request')
        ->setAttribute('http.method', $request->method())
        ->setAttribute('http.url', $request->fullUrl())
        ->startSpan();

    try {
        return $next($request);
    } finally {
        $span->end();
    }
}

Queue Job Tracing

// In your job class:
protected function handle(): void {
    $span = \OpenTelemetry\API\GlobalTracer::getTracer('laravel-queue')
        ->spanBuilder('process-job')
        ->setAttribute('job.name', static::class)
        ->startSpan();

    try {
        // Job logic
    } finally {
        $span->end();
    }
}

4. Resource and Attributes

Set Service/Deployment Attributes

use OpenTelemetry\API\Common\Instrumentation\ResourceInfo;

$resource = ResourceInfo::create([
    'service.name' => 'my-laravel-app',
    'service.version' => '1.0.0',
    'deployment.environment' => app()->environment(),
]);

\OpenTelemetry\API\GlobalResource::setResource($resource);

Semantic Conventions

Use standardized attribute names (e.g., http.method, db.system, db.name) for compatibility with observability tools.


Gotchas and Tips

Pitfalls

  1. API vs. SDK Confusion

    • This package is only the API. You must install an SDK (e.g., open-telemetry/sdk) to actually export data.
    • Example:
      composer require open-telemetry/api open-telemetry/sdk
      
  2. Context Leaks

    • Avoid holding spans/meters globally. Use Span::end() and Context::restore() to prevent memory leaks.
    • Bad:
      $globalSpan = $tracer->spanBuilder('bad')->startSpan(); // Leaks!
      
    • Good:
      $span = $tracer->spanBuilder('good')->startSpan();
      try { /* ... */ } finally { $span->end(); }
      
  3. Deprecated Interfaces

    • InstrumentationInterface and ConfigurationResolver are deprecated (since v1.9.0). Use AutoInstrumentation instead.
  4. Attribute Validation

    • Attributes must be homogeneous (e.g., ['key' => ['a', 'b']] is invalid). Use arrays of scalars:
      $span->setAttribute('tags', ['tag1', 'tag2']); // ✅
      $span->setAttribute('invalid', ['mixed' => ['a', 1]]); // ❌
      
  5. Propagator Mismatches

    • Ensure propagators (e.g., TextMapPropagator) are consistent across services. Mixing B3 and W3C formats can break tracing.

Debugging Tips

  1. Enable Logging Add to .env:

    OTEL_LOG_LEVEL=debug
    

    Logs will show SDK/API interactions (e.g., span creation, export failures).

  2. Validate Spans Use the Span::isRecording() check to verify spans are active:

    if (!$span->isRecording()) {
        throw new \RuntimeException('Span is not recording!');
    }
    
  3. Check Context Inspect the current context to debug propagation:

    $context = \OpenTelemetry\Context\Context::getCurrent();
    $span = \OpenTelemetry\Context\Span::getCurrentSpan($context);
    dump($span ? $span->getName() : 'No active span');
    
  4. OTLP Exporter Issues If traces/metrics don’t appear in your backend:

    • Verify the endpoint (OTEL_EXPORTER_OTLP_ENDPOINT).
    • Check for network/firewall blocks (OTLP uses gRPC/HTTP).
    • Test with curl:
      curl -X POST http://otel-collector:4317/v1/traces -H "Content-Type: application/x-protobuf"
      

Extension Points

  1. Custom Span Processors Filter or modify spans before export:
    use OpenTelemetry\SDK\Trace\SpanProcessor\SpanProcessorInterface;
    
    class MySpanProcessor implements SpanProcessorInterface {
        public function onStart(\OpenTelemetry\SDK\Trace\SpanData $span):
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport