larasahib/application-insights-laravel 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

larasahib/application-insights-laravel

Composer 安装命令:

composer require larasahib/application-insights-laravel

包简介

Microsoft Azure Application Insights for Laravel 10

README 文档

README

A simple Laravel integration for Microsoft Application Insights

This package was originally inspired by provisions-group/ms-application-insights-laravel. That package was built for Laravel 5 and is no longer maintained.

This package is a fully maintained, standalone implementation for Laravel 10+, updated to support the latest Application Insights requirements. It provides a clean way to push telemetry from your Laravel web app and APIs directly to Application Insights, with additional features such as queue support and separate handling for API and web guards.

Installation

Update the require section of your application's composer.json file:

"require": {
	...
	"larasahib/application-insights-laravel": "1.2.0",
	...
}

Instrumentation Key / Connection String

The package will check your application's .env file for your Instrumentation Key.

Note: MS_INSTRUMENTATION_KEY is deprecated. Use MS_AI_CONNECTION_STRING instead.

.env example

# Old way (deprecated)
# MS_INSTRUMENTATION_KEY=00000000-0000-0000-0000-000000000000

# New way (recommended)
MS_AI_CONNECTION_STRING=InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://<region>.in.applicationinsights.azure.com/

Where to find the connection string

You can get the connection string from your Azure Portal:

Application Insights → Overview → Connection String

You can find your instrumentation key on the Microsoft Azure Portal.

Navigate to:

Microsoft Azure > Browse > Application Insights > (Application Name) > Settings > Properties

Usage

Request Tracking Middleware

To monitor your application's performance with request tracking, add the middleware to your in your application, found in app/Http/Kernel.php. It has to be added after the StartSession middleware has been added.

protected $middleware = [
	'api':
		...
		'AppInsightsApiMiddleware',
		...
	'web':
		...
		'AppInsightsWebMiddleware',
		...
]

The request will send the following additional properties to Application Insights:

  • ajax (boolean): true if the request is an AJAX request
  • ip (string): The client's IP address
  • pjax (boolean): true if the request is a PJAX request
  • secure (boolean): true if the request was sent over HTTPS
  • route (string): The name of the route, if applicable
  • user (integer): The ID of the logged in user, if applicable
  • referer (string): The HTTP_REFERER value from the request, if available

The middleware is also used to estimate the time that a user has spent on a particular page. This is sent as a trace event named browse_duration.

Exception Handler

To report exceptions that occur in your application, use the provided exception handler. Replace the following line in your application's app/Handlers/Exception.php file:

...

# Delete this line
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

# Insert this line
use Larasahib\AppInsightsLaravel\Handlers\AppInsightsExceptionHandler as ExceptionHandler;

...

The exception handler will send additional properties to Application Insights, as above.

Client Side

In order to register page view information from the client with Application Insights, simply insert the following code into your Blade views:

{!! \AIClient::javascript() !!}

NOTE: Microsoft recommend that you put the script in the <head> section of your pages, in order to calculate the fullest extent of page load time on the client.

Custom

If you want to use any of the underlying ApplicationInsights-PHP functionality, you can call the methods directly from the server facade:

...
\AIServer::trackEvent('Test event');
\AIServer::flush();//immediate send
\AIQueue::dispatch(\AIServer::getChannel()->getQueue())->delay(now()->addSeconds(3));//use laravel queue to send data later
...

Publishing the Package Configuration and Assets

After installing the package, you need to publish the configuration file and JavaScript assets so your application can use them:

  1. Publish the configuration:
php artisan vendor:publish --tag=config

This will copy the AppInsightsLaravel.php configuration file to your app’s config folder.

2. Publish the JavaScript assets

Although Laravel 10+ users will have the assets automatically available after install or update via Composer, you can also manually publish them if needed:

php artisan vendor:publish --tag=laravel-assets

This ensures the JS file is copied to your public/vendor/appinsights/js folder and ready to be loaded by the client.

Tip: Add --force to overwrite existing files if needed.

📦 Version History

dev-master

  • Initial commit with basic Laravel integration.
  • Included dependency on microsoft/application-insights.

📦 1.0.1

  • First stable release.
  • Basic support for tracking requests and exceptions using Microsoft Application Insights PHP SDK.
  • Registered Laravel service provider and middleware for web & API.

📦 1.0.2

  • Refactored and renamed internal classes to avoid naming conflicts and improve maintainability.
  • Improved configuration publishing and service bindings.

📦 1.0.3

  • Added queue support via AppInsightsTelemetryQueue.
  • Enabled asynchronous event logging using Laravel queues.

📦 1.0.4

  • Minor fixes to config merging and bootstrapping.
  • Added ability to set instrumentation key via environment variable.

📦 1.0.5

  • Fixed service provider registration issues in Laravel 12.
  • Added support for Laravel's config:cache.

📦 1.0.6

  • Deprecated usage of microsoft/application-insights SDK.
  • Prepared for a complete rewrite using a custom telemetry client.

🚀 1.0.7

  • Replaced dependency on the deprecated Application Insights SDK with a custom-built HTTP client.

  • Implemented custom Telemetry_Client class compatible with Application Insights ingestion API.

  • ✅ Support for tracking:

    • Requests
    • Exceptions
    • Custom Events
    • Traces (Logs)
  • ✅ Introduced flush() mechanism with NDJSON batching.

  • ✅ Removed reliance on outdated or unsupported packages.

  • ✅ Maintained backward compatibility with existing service provider and class interfaces.

  • 🧪 Enhanced logging and error handling for production robustness.

🚀 1.1.8

  • Introduced auto-publishable JavaScript assets (appinsights-client.js) for client-side telemetry.

  • Improved client-side telemetry integration: Use AppInsightsClient::javascript() to include the JS in your pages.

  • Backend telemetry endpoint included to receive telemetry data sent from the JS.

1.1.9

  • ✅ **Adde appinsights-queue to add onto this queue when AI jobs are queued

  • 📝 New setup instructions:

    1. Publish the configuration file:
    php artisan vendor:publish --tag=config

2. Publish the JavaScript assets

Although Laravel 10+ users will have the assets automatically available after install or update via Composer, you can also manually publish them if needed:

php artisan vendor:publish --tag=laravel-assets

3. **Run a separate worker for only processin AI jobs

php artisan queue:work --queue=appinsights-queue

This ensures the JS file is copied to your public/vendor/appinsights/js folder and ready to be loaded by the client.

Tip: Add --force to overwrite existing files if needed.

  • Maintained backward compatibility with Laravel 10+ and previous package versions.

  • 🧪 Improved logging and error handling for both server-side and client-side telemetry.

  • 🛠 Minor bug fixes and internal refactors.

Release Notes

v1.2.2 (February 28, 2026)

  • Dependency telemetry: Added trackDependency support in the telemetry client to send dependency payloads (e.g., SQL, HTTP) with properties and measurements.
  • Automatic DB tracking: Service provider now hooks Laravel's query listener to emit SQL dependency telemetry when MS_AI_ENABLE_DEPENDENCY_TELEMETRY is enabled.
  • Config toggles: New config flags to enable dependency telemetry and optionally include query bindings (MS_AI_DB_DEP_BINDINGS).

v1.2.1 (January 26, 2026)

  • Fix for Empty Properties: Fixed an issue where telemetry was rejected when properties were empty. These are now correctly cast to objects to ensure proper JSON serialization ({} instead of []).
  • Improved Request Context in Exceptions: Added a fallback to capture request data using the Laravel request() helper when the request object is missing from the exception's stack trace, which is common in production environments.

v1.2.0 (January 19, 2026)

  • Production Reporting Fix: Fixed an issue where exceptions were not reported when the application was in production mode.
  • Centralized Logging: Refactored logging to use a centralized Logger class that respects the enable_local_logging configuration.
  • Improved Exception Tracing: Updated trackException to properly capture and merge request context and custom properties.
  • Stability Enhancements: Improved robustness of the telemetry flush mechanism and fixed potential runtime exceptions related to missing configuration.
  • Cleanup: Removed redundant logging and improved code readability.

larasahib/application-insights-laravel 适用场景与选型建议

larasahib/application-insights-laravel 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 22.96k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2023 年 11 月 02 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「logging」 「monitoring」 「azure」 「laravel」 「microsoft」 「Application Insights」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 larasahib/application-insights-laravel 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 larasahib/application-insights-laravel 我们能提供哪些服务?
定制开发 / 二次开发

基于 larasahib/application-insights-laravel 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 22.96k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 35
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-11-02