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.
Installation
composer require microsoft/app-insights-php
Ensure your Laravel project meets the updated PHP version requirements (8.1 or 8.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;
});
}
First Use Case: Track an Exception
try {
// Risky operation
} catch (\Exception $e) {
app(TelemetryClient::class)->trackException($e);
}
Configuration
Add to config/app-insights.php:
return [
'instrumentationKey' => env('APP_INSIGHTS_INSTRUMENTATION_KEY'),
'disable' => env('APP_INSIGHTS_DISABLE', false),
];
Bind the TelemetryClient to Laravel’s container for seamless use:
// In a controller or service
public function __construct(private TelemetryClient $telemetryClient) {}
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;
}
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,
]);
}
Track custom metrics for performance monitoring:
// Log a custom metric (e.g., queue processing time)
app(TelemetryClient::class)->trackMetric('queue.processing.time', $processingTimeMs);
Attach context (e.g., user ID, session) to telemetry:
$telemetryClient->context().user->id = auth()->id();
$telemetryClient->trackTrace('User action', SeverityLevel::Information);
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.
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.
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.');
}
Performance Overhead Disable telemetry in production if unused:
if (!config('app-insights.disable')) {
app(TelemetryClient::class)->trackEvent('App Loaded');
}
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:
Custom Telemetry Types
Extend the client to support custom telemetry (e.g., trackLaravelJob):
$telemetryClient->trackCustomEvent('laravel.job', [
'job' => $job->getName(),
'queue' => $job->queue,
]);
Sampling Implement sampling to reduce telemetry volume:
if (random_int(0, 99) < 10) { // 10% sampling
$telemetryClient->trackEvent('Sampled Event');
}
Integration with Laravel Debugbar Display App Insights data in the Debugbar panel for local development:
Debugbar::info([
'app_insights' => [
'telemetry_count' => $telemetryClient->getTelemetryCount(),
],
]);
env() with fallbacks:
'instrumentationKey' => env('APP_INSIGHTS_KEY_STAGING', env('APP_INSIGHTS_KEY_PROD')),
APP_INSIGHTS_DISABLE=true in .env for local/dev environments.operationId for distributed tracing:
$telemetryClient->context().operationId = Str::uuid()->toString();
public function report(Throwable $exception)
{
app(TelemetryClient::class)->trackException($exception);
parent::report($exception);
}
FailedJob::failed(function ($event) {
app(TelemetryClient::class)->trackException(
new \Exception("Queue job failed: {$event->job}")
);
});
How can I help you explore Laravel packages today?