app-insights-php/app-insights-php-bundle
Install the Bundle
composer require app-insights-php/app-insights-php-bundle
Configure config/packages/app_insights.yaml
app_insights:
instrumentation_key: "YOUR_INSTRUMENTATION_KEY"
environment: "%env(APP_ENV)%"
disabled: "%kernel.debug%" # Disable in dev mode
Enable the Bundle
Add to config/bundles.php:
return [
// ...
AppInsightsPHPBundle\AppInsightsPHPBundle::class => ['all' => true],
];
First Use Case: Track Requests The bundle auto-instruments HTTP requests. Verify in Azure Portal under Requests after deploying.
config/packages/monolog.yaml):
handlers:
app_insights:
type: service
id: app_insights.monolog.handler
level: debug
$this->logger->info('User login attempt', ['user_id' => 123, 'ip' => $request->getClientIp()]);
ExceptionListener. For CLI:
use AppInsightsPHPBundle\Telemetry\TelemetryClient;
try {
// Risky code
} catch (\Exception $e) {
TelemetryClient::trackException($e);
throw $e;
}
TelemetryClient::trackEvent('OrderCreated', [
'order_id' => $order->id,
'amount' => $order->total,
]);
Connection events. Add to config/packages/doctrine.yaml:
dbal:
connections:
default:
logging: true # Enable SQL logging
{% app_insights_page_view 'homepage' %}
config/packages/app_insights.yaml:
cli:
enabled: true
TelemetryClient::trackTrace('CLI command executed', ['command' => 'app:export']);
Disable telemetry for specific routes:
# config/packages/app_insights.yaml
disabled_routes:
- ^/admin/health
Attach context to all telemetry:
TelemetryClient::setContext(['user_id' => $currentUser->id]);
Manually track HTTP dependencies:
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.example.com/data');
TelemetryClient::trackDependency(
'HTTP',
'GET',
'api.example.com/data',
(string) $response->getEffectiveUri(),
$response->getStatusCode(),
$response->getHeaderLine('Content-Type'),
(int) $response->getHeader('X-Response-Time')[0]
);
Track custom metrics (e.g., queue length):
TelemetryClient::trackMetric('queue_length', count($queue));
Instrumentation Key Leaks
instrumentation_key to version control. Use environment variables:
# .env
APP_INSIGHTS_INSTRUMENTATION_KEY=your_key_here
app_insights:
instrumentation_key: "%env(APP_INSIGHTS_INSTRUMENTATION_KEY)%"
Performance Overhead
dev mode (disabled: "%kernel.debug%").app_insights:
sampling_percentage: 10 # Track 10% of requests
Doctrine SQL Logging
logging: true in Doctrine config to capture SQL queries as dependencies.CLI Telemetry Double-Counting
cli:
enabled: false
Telemetry Queue Backlog
app_insights:
cache:
path: "%kernel.cache_dir%/app_insights"
max_size: 100MB # Limit cache size
Verify Telemetry in Azure Portal
requests | take 10
traces | take 10
Local Testing
Log Fallback
app_insights:
fallback_logger: true # Logs to Monolog if App Insights fails
Common Issues
disabled_routes or disabled config.logging: true and the doctrine extension is enabled in app_insights.yaml:
extensions:
doctrine: true
Custom Telemetry Listeners
AppInsightsPHPBundle\EventListener\TelemetryListenerInterface to add custom logic:
use AppInsightsPHPBundle\EventListener\TelemetryListenerInterface;
use AppInsightsPHPBundle\Telemetry\TelemetryClient;
class CustomTelemetryListener implements TelemetryListenerInterface
{
public function onKernelRequest(GetResponseEvent $event)
{
TelemetryClient::trackTrace('Custom request event', ['route' => $event->getRequest()->getPathInfo()]);
}
}
services.yaml:
services:
App\EventListener\CustomTelemetryListener:
tags:
- { name: 'kernel.event_listener', event: 'kernel.request', method: 'onKernelRequest' }
Override Telemetry Client
services.yaml:
services:
AppInsightsPHPBundle\Telemetry\TelemetryClient:
class: App\Telemetry\CustomTelemetryClient
Custom Monolog Handler
AppInsightsHandler to filter logs:
use AppInsightsPHPBundle\Monolog\AppInsightsHandler;
class CustomAppInsightsHandler extends AppInsightsHandler
{
protected function isLogable(array $record): bool
{
return strpos($record['message'], 'sensitive') === false;
}
}
monolog.yaml:
handlers:
custom_app_insights:
type: service
id: App\Monolog\CustomAppInsightsHandler
level: debug
Correlate Frontend/Backend
operation_id in JavaScript and PHP:
// JavaScript (App Insights SDK)
appInsights.context.tags[appInsights.defaultTelemetryProcessor.operationIdTagName] = 'PHP_OPERATION_ID';
// PHP
TelemetryClient::setContext(['operation_id' => 'PHP_OPERATION_ID']);
Custom Dashboards
requests | summarize avg(duration))exceptions | summarize count())Alert Rules
exceptions | where timestamp > ago(5m) | count > 5)requests | where duration > 1000 | count)Sampling Strategies
How can I help you explore Laravel packages today?