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

Monolog Handler Laravel Package

app-insights-php/monolog-handler

Monolog handlers for Microsoft Application Insights: send traces and dependency telemetry via AppInsightsTraceHandler and AppInsightsDependencyHandler. Supports buffering for long-running workers and enforces the 64KB telemetry size limit. Includes Laravel setup example.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require app-insights-php/monolog-handler
    

    Ensure monolog/monolog is also installed (dependency).

  2. Basic Configuration Add the handler to your Laravel config/logging.php under channels:

    'app_insights' => [
        'driver' => 'custom',
        'via' => \App\Insights\Monolog\AppInsightsHandler::class,
        'config' => [
            'instrumentation_key' => env('APPINSIGHTS_INSTRUMENTATION_KEY'),
            'telemetry_channel' => env('APPINSIGHTS_TELEMETRY_CHANNEL', 'Live'),
            'log_level' => env('APPINSIGHTS_LOG_LEVEL', \Monolog\Logger::DEBUG),
        ],
    ],
    
  3. First Use Case Log a test event in a controller or service:

    use Illuminate\Support\Facades\Log;
    
    Log::channel('app_insights')->info('User login attempt', [
        'user_id' => auth()->id(),
        'ip' => request()->ip(),
    ]);
    

Implementation Patterns

Workflows

  1. Structured Logging Leverage Monolog’s context for rich telemetry:

    Log::channel('app_insights')->error('Payment failed', [
        'amount' => $amount,
        'gateway' => 'stripe',
        'error' => $exception->getMessage(),
    ]);
    
  2. Exception Tracking Use Laravel’s exception handler to auto-log errors:

    // app/Exceptions/Handler.php
    public function report(Throwable $exception)
    {
        Log::channel('app_insights')->error('Unhandled exception', [
            'exception' => get_class($exception),
            'message' => $exception->getMessage(),
            'trace' => $exception->getTraceAsString(),
        ]);
    }
    
  3. Performance Monitoring Track request durations with start/stop timestamps:

    $start = microtime(true);
    // ... business logic ...
    Log::channel('app_insights')->info('Request completed', [
        'duration_ms' => (microtime(true) - $start) * 1000,
        'route' => request()->path(),
    ]);
    

Integration Tips

  • Laravel Logging Facade: Prefer Log::channel('app_insights') over direct handler instantiation for consistency.
  • Environment Awareness: Disable in local environments via config:
    'config' => [
        'enabled' => !app()->environment('local'),
        // ...
    ],
    
  • Batch Processing: Configure telemetry_channel to Server for offline batch uploads:
    'telemetry_channel' => env('APPINSIGHTS_TELEMETRY_CHANNEL', 'Server'),
    

Gotchas and Tips

Pitfalls

  1. Instrumentation Key Leaks Avoid hardcoding keys; use Laravel’s .env and validate presence:

    if (empty(config('logging.channels.app_insights.config.instrumentation_key'))) {
        throw new \RuntimeException('App Insights key not configured.');
    }
    
  2. Telemetry Throttling App Insights may throttle high-volume logs. Use log_level to filter noise:

    'log_level' => \Monolog\Logger::WARNING, // Only log warnings/errors
    
  3. Archived Package Risks

    • No active maintenance; test thoroughly in staging.
    • Fork or extend locally if critical bugs arise (MIT license permits).

Debugging

  • Verify Logs in Portal: Check Azure Portal under Application Insights > Logs for missing entries.
  • Handler Initialization: Debug handler setup with:
    \App\Insights\Monolog\AppInsightsHandler::getTelemetryClient()->trackTrace('Test trace');
    
  • Network Issues: Ensure outbound traffic to dc.services.visualstudio.com is allowed.

Extension Points

  1. Custom Telemetry Extend the handler to add custom properties:

    // app/Insights/Monolog/CustomAppInsightsHandler.php
    class CustomAppInsightsHandler extends AppInsightsHandler
    {
        protected function getContext(): array
        {
            return array_merge(parent::getContext(), [
                'custom_dimension' => 'value',
            ]);
        }
    }
    
  2. Sampling Implement sampling logic in isHandling():

    public function isHandling(array $record): bool
    {
        return mt_rand(1, 100) <= 10; // 10% sampling
    }
    
  3. Async Writes Use Laravel’s queue system to offload telemetry:

    Log::channel('app_insights')->pushHandler(
        new \App\Insights\Monolog\QueuedAppInsightsHandler(
            new AppInsightsHandler($config),
            new \Illuminate\Contracts\Queue\Queue
        )
    );
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui