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

App Insights Php Bundle Laravel Package

app-insights-php/app-insights-php-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require app-insights-php/app-insights-php-bundle
    
  2. Configure config/packages/app_insights.yaml

    app_insights:
        instrumentation_key: "YOUR_INSTRUMENTATION_KEY"
        environment: "%env(APP_ENV)%"
        disabled: "%kernel.debug%"  # Disable in dev mode
    
  3. Enable the Bundle Add to config/bundles.php:

    return [
        // ...
        AppInsightsPHPBundle\AppInsightsPHPBundle::class => ['all' => true],
    ];
    
  4. First Use Case: Track Requests The bundle auto-instruments HTTP requests. Verify in Azure Portal under Requests after deploying.


Implementation Patterns

Core Workflows

1. Logging with Monolog

  • Add App Insights Handler to your Monolog configuration (config/packages/monolog.yaml):
    handlers:
        app_insights:
            type: service
            id: app_insights.monolog.handler
            level: debug
    
  • Log custom traces:
    $this->logger->info('User login attempt', ['user_id' => 123, 'ip' => $request->getClientIp()]);
    

2. Tracking Exceptions

  • Auto-captured via Symfony’s ExceptionListener. For CLI:
    use AppInsightsPHPBundle\Telemetry\TelemetryClient;
    
    try {
        // Risky code
    } catch (\Exception $e) {
        TelemetryClient::trackException($e);
        throw $e;
    }
    

3. Custom Events

  • Track business events:
    TelemetryClient::trackEvent('OrderCreated', [
        'order_id' => $order->id,
        'amount' => $order->total,
    ]);
    

4. Database Dependencies (Doctrine)

  • Auto-instrumented via Doctrine’s Connection events. Add to config/packages/doctrine.yaml:
    dbal:
        connections:
            default:
                logging: true  # Enable SQL logging
    

5. Twig Integration

  • Track page views in templates:
    {% app_insights_page_view 'homepage' %}
    

6. CLI Telemetry

  • Enable CLI tracking in config/packages/app_insights.yaml:
    cli:
        enabled: true
    
  • Track CLI commands:
    TelemetryClient::trackTrace('CLI command executed', ['command' => 'app:export']);
    

Advanced Patterns

Conditional Tracking

Disable telemetry for specific routes:

# config/packages/app_insights.yaml
disabled_routes:
    - ^/admin/health

Custom Telemetry Properties

Attach context to all telemetry:

TelemetryClient::setContext(['user_id' => $currentUser->id]);

Dependency Tracking for External APIs

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]
);

Custom Metrics

Track custom metrics (e.g., queue length):

TelemetryClient::trackMetric('queue_length', count($queue));

Gotchas and Tips

Pitfalls

  1. Instrumentation Key Leaks

    • Never commit instrumentation_key to version control. Use environment variables:
      # .env
      APP_INSIGHTS_INSTRUMENTATION_KEY=your_key_here
      
    • Override in config:
      app_insights:
          instrumentation_key: "%env(APP_INSIGHTS_INSTRUMENTATION_KEY)%"
      
  2. Performance Overhead

    • Disable in dev mode (disabled: "%kernel.debug%").
    • For high-traffic APIs, batch telemetry calls or use sampling:
      app_insights:
          sampling_percentage: 10  # Track 10% of requests
      
  3. Doctrine SQL Logging

    • Ensure logging: true in Doctrine config to capture SQL queries as dependencies.
  4. CLI Telemetry Double-Counting

    • Disable CLI telemetry if using a separate monitoring tool:
      cli:
          enabled: false
      
  5. Telemetry Queue Backlog

    • If App Insights is unreachable, telemetry is cached locally. Monitor disk usage:
      app_insights:
          cache:
              path: "%kernel.cache_dir%/app_insights"
              max_size: 100MB  # Limit cache size
      

Debugging Tips

  1. Verify Telemetry in Azure Portal

    • Check Logs (Analytics) in Azure Portal:
      requests | take 10
      traces    | take 10
      
  2. Local Testing

  3. Log Fallback

    • Configure a fallback logger for uncaught telemetry errors:
      app_insights:
          fallback_logger: true  # Logs to Monolog if App Insights fails
      
  4. Common Issues

    • No data appearing?
      • Check disabled_routes or disabled config.
      • Verify the instrumentation key is correct.
    • High latency?
      • Reduce sampling percentage or batch telemetry calls.
    • SQL queries missing?
      • Ensure Doctrine’s logging: true and the doctrine extension is enabled in app_insights.yaml:
        extensions:
            doctrine: true
        

Extension Points

  1. Custom Telemetry Listeners

    • Implement 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()]);
          }
      }
      
    • Register in services.yaml:
      services:
          App\EventListener\CustomTelemetryListener:
              tags:
                  - { name: 'kernel.event_listener', event: 'kernel.request', method: 'onKernelRequest' }
      
  2. Override Telemetry Client

    • Replace the default client in services.yaml:
      services:
          AppInsightsPHPBundle\Telemetry\TelemetryClient:
              class: App\Telemetry\CustomTelemetryClient
      
  3. Custom Monolog Handler

    • Extend AppInsightsHandler to filter logs:
      use AppInsightsPHPBundle\Monolog\AppInsightsHandler;
      
      class CustomAppInsightsHandler extends AppInsightsHandler
      {
          protected function isLogable(array $record): bool
          {
              return strpos($record['message'], 'sensitive') === false;
          }
      }
      
    • Register in monolog.yaml:
      handlers:
          custom_app_insights:
              type: service
              id: App\Monolog\CustomAppInsightsHandler
              level: debug
      

Pro Tips

  1. Correlate Frontend/Backend

    • Use the same 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']);
      
  2. Custom Dashboards

    • Use Azure Portal’s Metrics Explorer to create custom dashboards for:
      • Response times (requests | summarize avg(duration))
      • Error rates (exceptions | summarize count())
  3. Alert Rules

    • Set up alerts for:
      • High error rates (exceptions | where timestamp > ago(5m) | count > 5)
      • Slow requests (requests | where duration > 1000 | count)
  4. Sampling Strategies

    • For
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware