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

Instana Php Opentracing Laravel Package

instana/instana-php-opentracing

Instana’s OpenTracing implementation for PHP. Send traces to an Instana Agent via the PHP sensor (default port 16816) or REST SDK endpoint (port 42699). Provides InstanaTracer helpers, tags, and span types for instrumenting PHP apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require instana/instana-php-opentracing
    

    Add the autoloader to your project if not using PSR-4.

  2. Basic Initialization Locate the InstanaTracer class and initialize it with your Instana agent configuration:

    use Instana\InstanaTracer;
    
    $tracer = InstanaTracer::getTracer(
        'your-instana-agent-host',
        42699, // Default Instana agent port
        'your-application-name',
        '1.0.0' // Application version
    );
    
  3. First Use Case: Instrumenting a Request Wrap your request handling logic in a span:

    $span = $tracer->buildSpan('handle-request')->start();
    try {
        // Your request logic here
        $result = doSomething();
    } finally {
        $span->finish();
    }
    

Where to Look First

  • Documentation: Check the Instana PHP OpenTracing docs for agent-specific setup.
  • Tracer Configuration: Review InstanaTracer::getTracer() parameters for customization (e.g., sampling rate, tags).
  • Span Context: Explore SpanContext for propagating traces across services (e.g., HTTP clients).
  • Span Types: Review updated InstanaSpanType methods (entryType(), localType(), exitType()) for semantic span classification.

Implementation Patterns

Workflow: Instrumenting a Laravel Controller

  1. Middleware for Automatic Tracing Create middleware to auto-instrument requests:

    namespace App\Http\Middleware;
    
    use Closure;
    use Instana\InstanaTracer;
    
    class TraceRequests
    {
        public function handle($request, Closure $next)
        {
            $tracer = InstanaTracer::getTracer(...);
            $span = $tracer->buildSpan('HTTP ' . $request->method() . ' ' . $request->path())
                ->withTag('http.method', $request->method())
                ->withTag('http.url', $request->fullUrl())
                ->start();
    
            try {
                return $next($request);
            } finally {
                $span->finish();
            }
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        \App\Http\Middleware\TraceRequests::class,
    ];
    
  2. Service-Level Instrumentation with Span Types Use semantic span types for better trace visualization:

    $span = $tracer->buildSpan('fetch-user')
        ->asType(InstanaSpanType::exitType()) // Mark as external call
        ->start();
    try {
        $user = User::find($id);
    } finally {
        $span->finish();
    }
    
  3. Propagating Context Use SpanContext to pass traces to downstream services (e.g., HTTP clients):

    $context = $span->getContext();
    $client = new HttpClient();
    $response = $client->request('GET', $url, [
        'headers' => [
            'uber-trace-id' => $context->getTraceId(),
        ],
    ]);
    

Integration Tips

  • Queue Workers: Instrument queue jobs by wrapping handle() in spans with appropriate types:
    $span = $tracer->buildSpan('process-order')
        ->asType(InstanaSpanType::localType()) // Mark as internal processing
        ->start();
    try {
        // Job logic
    } finally {
        $span->finish();
    }
    
  • Exceptions: Add error spans for unhandled exceptions:
    try {
        // Logic
    } catch (\Exception $e) {
        $span->log(['event' => 'error', 'message' => $e->getMessage()]);
        $span->setTag('error', true);
        throw $e;
    }
    
  • Custom Metrics: Use Span::setTag() for business metrics (e.g., cart_items: 3).

Gotchas and Tips

Pitfalls

  1. Agent Connectivity

    • Issue: Spans may not appear in Instana if the agent is unreachable.
    • Fix: Verify the agent host/port and network connectivity. Use InstanaTracer::getTracer() with false for the host to disable tracing (for testing).
  2. Context Propagation

    • Issue: Traces break if SpanContext isn’t propagated to downstream services.
    • Fix: Ensure headers like uber-trace-id are forwarded in HTTP requests. Use libraries like opentracing-contrib/php-http for automatic propagation.
  3. Sampling Rate

    • Issue: High-volume apps may overwhelm Instana with too many spans.
    • Fix: Configure sampling in InstanaTracer:
      $tracer = InstanaTracer::getTracer(..., 0.1); // Sample 10% of traces
      
  4. Span Lifecycle

    • Issue: Unfinished spans (e.g., due to uncaught exceptions) create "orphaned" traces.
    • Fix: Use finally blocks or Laravel’s illuminate/support/helpers:
      $span = $tracer->buildSpan('task')->start();
      try {
          // Work
      } finally {
          $span->finish();
      }
      
  5. Deprecated Methods (v2.0.0)

    • Issue: The package renamed InstanaSpanType::entry(), InstanaSpanType::local(), and InstanaSpanType::exit() to entryType(), localType(), and exitType() for PHP < 7 compatibility.
    • Fix: Update all span type assignments to use the new method names:
      // Old (deprecated in v2.0.0)
      $span->asType(InstanaSpanType::entry());
      
      // New (v2.0.0+)
      $span->asType(InstanaSpanType::entryType());
      

Debugging

  • Check Tracer Status: Log the tracer’s active state:
    \Log::debug('Tracer active:', ['active' => $tracer->isActive()]);
    
  • Span IDs: Log SpanContext to correlate traces:
    \Log::debug('Trace ID:', [$span->getContext()->getTraceId()]);
    
  • Agent Logs: Check Instana agent logs (/var/log/instana/agent.log) for connection issues.

Extension Points

  1. Custom Tags Extend InstanaTracer to add application-specific tags:

    $span->withTag('user.role', auth()->user()->role);
    
  2. Global Tracer Instance Bind the tracer to Laravel’s container for DI:

    $app->singleton(InstanaTracer::class, function () {
        return InstanaTracer::getTracer(...);
    });
    
  3. Testing Mock the tracer in tests:

    $this->app->instance(InstanaTracer::class, Mockery::mock(InstanaTracer::class));
    

Config Quirks

  • Environment Variables: Store agent host/port in .env:

    INSTANA_AGENT_HOST=instana-agent
    INSTANA_AGENT_PORT=42699
    

    Then load them dynamically:

    $tracer = InstanaTracer::getTracer(
        env('INSTANA_AGENT_HOST'),
        env('INSTANA_AGENT_PORT', 42699),
        ...
    );
    
  • Span Type Usage Use semantic span types (entryType(), localType(), exitType()) to improve trace readability:

    • entryType(): For incoming requests (e.g., HTTP endpoints).
    • localType(): For internal processing (e.g., business logic).
    • exitType(): For outgoing calls (e.g., database queries, API calls).
  • Deprecated Methods: Avoid using the old InstanaSpanType::entry(), InstanaSpanType::local(), and InstanaSpanType::exit() methods in new code. Update existing code to use the new method names.

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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity