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

Client Laravel Package

app-insights-php/client

PHP wrapper for microsoft/application-insights that provides a configurable telemetry client for Microsoft App Insights. Simplifies integration (incl. bundle use) and validates telemetry against the 64KB size limit, throwing exceptions when exceeded.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require microsoft/app-insights-php
    

    Ensure your Laravel project meets the updated PHP version requirements (8.1 or 8.2).

  2. Basic Initialization Create a service provider (e.g., AppInsightsServiceProvider) to bootstrap the client:

    use Microsoft\ApplicationInsights\TelemetryClient;
    
    public function register()
    {
        $this->app->singleton(TelemetryClient::class, function ($app) {
            $client = new TelemetryClient(
                config('app-insights.instrumentationKey')
            );
            return $client;
        });
    }
    
  3. First Use Case: Track an Exception

    try {
        // Risky operation
    } catch (\Exception $e) {
        app(TelemetryClient::class)->trackException($e);
    }
    
  4. Configuration Add to config/app-insights.php:

    return [
        'instrumentationKey' => env('APP_INSIGHTS_INSTRUMENTATION_KEY'),
        'disable' => env('APP_INSIGHTS_DISABLE', false),
    ];
    

Implementation Patterns

Dependency Injection

Bind the TelemetryClient to Laravel’s container for seamless use:

// In a controller or service
public function __construct(private TelemetryClient $telemetryClient) {}

Middleware for Automatic Tracking

Create middleware to log requests/responses:

public function handle($request, Closure $next)
{
    $telemetryClient = app(TelemetryClient::class);
    $telemetryClient->trackRequest($request->method(), $request->path());

    $response = $next($request);

    $telemetryClient->trackResponse(
        $request->path(),
        $response->getStatusCode(),
        $response->getContent()
    );

    return $response;
}

Event-Based Telemetry

Use Laravel events to log business-critical actions:

// In an event listener
public function handle(OrderPlaced $event)
{
    app(TelemetryClient::class)->trackEvent('Order Placed', [
        'order_id' => $event->order->id,
        'amount' => $event->order->amount,
    ]);
}

Custom Metrics

Track custom metrics for performance monitoring:

// Log a custom metric (e.g., queue processing time)
app(TelemetryClient::class)->trackMetric('queue.processing.time', $processingTimeMs);

Contextual Telemetry

Attach context (e.g., user ID, session) to telemetry:

$telemetryClient->context().user->id = auth()->id();
$telemetryClient->trackTrace('User action', SeverityLevel::Information);

Gotchas and Tips

Pitfalls

  1. PHP Version Compatibility The package now requires PHP 8.1 or 8.2. Update your Laravel project to avoid compatibility issues:

    composer require php:^8.1
    

    Check for deprecated syntax or removed features in your existing codebase.

  2. Archived Package Risk The package remains archived (no active maintenance). Validate compatibility with your Laravel version and PHP runtime. Consider forking or replacing if critical.

  3. Instrumentation Key Exposure Avoid hardcoding instrumentationKey in code. Use Laravel’s .env and validate it exists in config/app-insights.php:

    if (blank(config('app-insights.instrumentationKey'))) {
        throw new \RuntimeException('App Insights instrumentation key is missing.');
    }
    
  4. Performance Overhead Disable telemetry in production if unused:

    if (!config('app-insights.disable')) {
        app(TelemetryClient::class)->trackEvent('App Loaded');
    }
    

Debugging

  • Enable Debugging Set APP_INSIGHTS_DEBUG=true in .env to log telemetry client activity to Laravel’s log.

  • Validate Telemetry Use the Azure Portal to verify data ingestion. Check for:

    • Missing/incomplete data.
    • Incorrect context (e.g., user ID not attached).

Extension Points

  1. Custom Telemetry Types Extend the client to support custom telemetry (e.g., trackLaravelJob):

    $telemetryClient->trackCustomEvent('laravel.job', [
        'job' => $job->getName(),
        'queue' => $job->queue,
    ]);
    
  2. Sampling Implement sampling to reduce telemetry volume:

    if (random_int(0, 99) < 10) { // 10% sampling
        $telemetryClient->trackEvent('Sampled Event');
    }
    
  3. Integration with Laravel Debugbar Display App Insights data in the Debugbar panel for local development:

    Debugbar::info([
        'app_insights' => [
            'telemetry_count' => $telemetryClient->getTelemetryCount(),
        ],
    ]);
    

Config Quirks

  • Environment-Specific Keys Use env() with fallbacks:
    'instrumentationKey' => env('APP_INSIGHTS_KEY_STAGING', env('APP_INSIGHTS_KEY_PROD')),
    
  • Disable in Local Set APP_INSIGHTS_DISABLE=true in .env for local/dev environments.

Pro Tips

  • Correlate IDs Use operationId for distributed tracing:
    $telemetryClient->context().operationId = Str::uuid()->toString();
    
  • Log Laravel Exceptions Create a global exception handler:
    public function report(Throwable $exception)
    {
        app(TelemetryClient::class)->trackException($exception);
        parent::report($exception);
    }
    
  • Monitor Laravel Queues Log queue job failures:
    FailedJob::failed(function ($event) {
        app(TelemetryClient::class)->trackException(
            new \Exception("Queue job failed: {$event->job}")
        );
    });
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
christhompsontldr/laravel-inky
spatie/mailcoach-vapor