PHPackages                             larasahib/application-insights-laravel - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. larasahib/application-insights-laravel

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

larasahib/application-insights-laravel
======================================

Microsoft Azure Application Insights for Laravel 10

1.2.2(2mo ago)318.2k—3.6%1MITPHPPHP &gt;=8.1

Since Nov 2Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/GitSahib/application-insights-laravel)[ Packagist](https://packagist.org/packages/larasahib/application-insights-laravel)[ Docs](https://github.com/GitSahib/application-insights-laravel)[ RSS](/packages/larasahib-application-insights-laravel/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (34)Used By (0)

Microsoft Application Insights for Laravel 10+
==============================================

[](#microsoft-application-insights-for-laravel-10)

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
------------

[](#installation)

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

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

Instrumentation Key / Connection String
---------------------------------------

[](#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

[](#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://.in.applicationinsights.azure.com/
```

### Where to find the connection string

[](#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](https://portal.azure.com).

Navigate to:

**Microsoft Azure** &gt; **Browse** &gt; **Application Insights** &gt; *(Application Name)* &gt; **Settings** &gt; **Properties**

Usage
-----

[](#usage)

### Request Tracking Middleware

[](#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

[](#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

[](#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 `` section of your pages, in order to calculate the fullest extent of page load time on the client.

### Custom

[](#custom)

If you want to use any of the underlying [ApplicationInsights-PHP](https://github.com/Microsoft/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
-----------------------------------------------

[](#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**

[](#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

[](#-version-history)

#### ✅ **dev-master**

[](#-dev-master)

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

---

#### 📦 **1.0.1**

[](#-101)

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

---

#### 📦 **1.0.2**

[](#-102)

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

---

#### 📦 **1.0.3**

[](#-103)

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

---

#### 📦 **1.0.4**

[](#-104)

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

---

#### 📦 **1.0.5**

[](#-105)

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

---

#### 📦 **1.0.6**

[](#-106)

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

---

#### 🚀 **1.0.7**

[](#-107)

- ✅ **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**

[](#-118)

- ✅ **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**

[](#119)

- ✅ \*\*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**

[](#2-publish-the-javascript-assets-1)

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

[](#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
-------------

[](#release-notes)

### v1.2.1 (January 26, 2026)

[](#v121-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)

[](#v120-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.

---

###  Health Score

50

—

FairBetter than 96% of packages

Maintenance82

Actively maintained with recent releases

Popularity31

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~26 days

Recently: every ~10 days

Total

33

Last Release

79d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/17215394?v=4)[Sahib Zar Khan](/maintainers/GitSahib)[@GitSahib](https://github.com/GitSahib)

---

Top Contributors

[![GitSahib](https://avatars.githubusercontent.com/u/17215394?v=4)](https://github.com/GitSahib "GitSahib (29 commits)")

---

Tags

laravelloggingmonitoringmicrosoftazureApplication Insights

### Embed Badge

![Health badge](/badges/larasahib-application-insights-laravel/health.svg)

```
[![Health](https://phpackages.com/badges/larasahib-application-insights-laravel/health.svg)](https://phpackages.com/packages/larasahib-application-insights-laravel)
```

###  Alternatives

[marchie/ms-application-insights-laravel

Microsoft Azure Application Insights for Laravel 5

134.0k](/packages/marchie-ms-application-insights-laravel)[hosmelq/laravel-logsnag

Integrate the power of LogSnag's real-time event tracking into your Laravel application.

237.9k](/packages/hosmelq-laravel-logsnag)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
