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.
Installation
composer require app-insights-php/monolog-handler
Ensure monolog/monolog is also installed (dependency).
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),
],
],
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(),
]);
Structured Logging Leverage Monolog’s context for rich telemetry:
Log::channel('app_insights')->error('Payment failed', [
'amount' => $amount,
'gateway' => 'stripe',
'error' => $exception->getMessage(),
]);
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(),
]);
}
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(),
]);
Log::channel('app_insights') over direct handler instantiation for consistency.local environments via config:
'config' => [
'enabled' => !app()->environment('local'),
// ...
],
telemetry_channel to Server for offline batch uploads:
'telemetry_channel' => env('APPINSIGHTS_TELEMETRY_CHANNEL', 'Server'),
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.');
}
Telemetry Throttling
App Insights may throttle high-volume logs. Use log_level to filter noise:
'log_level' => \Monolog\Logger::WARNING, // Only log warnings/errors
Archived Package Risks
\App\Insights\Monolog\AppInsightsHandler::getTelemetryClient()->trackTrace('Test trace');
dc.services.visualstudio.com is allowed.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',
]);
}
}
Sampling
Implement sampling logic in isHandling():
public function isHandling(array $record): bool
{
return mt_rand(1, 100) <= 10; // 10% sampling
}
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
)
);
How can I help you explore Laravel packages today?