PHPackages                             davidmanassa/elastic-apm-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. davidmanassa/elastic-apm-laravel

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

davidmanassa/elastic-apm-laravel
================================

Laravel APM agent for Elastic v2 intake API

v1.0.4(1y ago)01.6kMITPHPPHP ^8.0.2

Since Jan 28Pushed 1y agoCompare

[ Source](https://github.com/davidmanassa/elastic-apm-laravel)[ Packagist](https://packagist.org/packages/davidmanassa/elastic-apm-laravel)[ RSS](/packages/davidmanassa-elastic-apm-laravel/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (14)Versions (6)Used By (0)

Elastic APM
===========

[](#elastic-apm)

[![CircleCI](https://camo.githubusercontent.com/8441cf71ac47ee89d430ca24cb48c54f48aa1a44686beffa413d4635423c5de1/68747470733a2f2f636972636c6563692e636f6d2f67682f61726b6169747a676172726f2f656c61737469632d61706d2d6c61726176656c2e7376673f7374796c653d737667)](https://circleci.com/gh/arkaitzgarro/elastic-apm-laravel)[![Latest Stable Version](https://camo.githubusercontent.com/80fdc82fb2e8167c781710d2cd3df10d8ba3bba4e1115dbeec3bf203cb777b64/68747470733a2f2f706f7365722e707567782e6f72672f61726b6169747a676172726f2f656c61737469632d61706d2d6c61726176656c2f762f737461626c65)](https://packagist.org/packages/arkaitzgarro/elastic-apm-laravel)[![Test Coverage](https://camo.githubusercontent.com/44105d52259ef036147f178909c303f73a3c9176b0c69c9983219dd6358be50b/68747470733a2f2f6170692e636f6465636c696d6174652e636f6d2f76312f6261646765732f65356136366239626635313631653239396338632f746573745f636f766572616765)](https://codeclimate.com/github/arkaitzgarro/elastic-apm-laravel/test_coverage)[![License](https://camo.githubusercontent.com/65e7a118abe2725633459852ed92de4b8d803d654c3ec56724d191bef43c8a5d/68747470733a2f2f706f7365722e707567782e6f72672f61726b6169747a676172726f2f656c61737469632d61706d2d6c61726176656c2f6c6963656e7365)](https://packagist.org/packages/arkaitzgarro/elastic-apm-laravel)

Elastic APM agent for v2 intake API. Compatible with Laravel 6+.

Transactions listTransaction detail[![](public/apm-transaction-list.png)](public/apm-transaction-list.png)[![](public/apm-transaction-detail.png)](public/apm-transaction-detail.png)Prerequisites
-------------

[](#prerequisites)

You are responsible for completing the following as part of installing this package.

### HTTP Client

[](#http-client)

In order to minimize potential dependency conflicts, this package does not dictate the HTTP client which will be used to send data to APM. Instead, your project must include a suitable [PSR-18](https://www.php-fig.org/psr/psr-18/) compatible implementation. The easiest way to do this is using the [php-http](http://docs.php-http.org/en/latest/) adapter for GuzzleHTTP. Require either the guzzle6 or guzzle7 adapter, depending on your specific needs.

```
    # if you are using guzzlehttp/guzzle version 6
    # note that you must use >=2.0 of the guzzle6-adapter
    composer require php-http/guzzle6-adapter
```

```
    # if you are using guzzlehttp/guzzle version 7
    composer require php-http/guzzle7-adapter
```

Installation
------------

[](#installation)

Require this package with composer:

```
# Laravel 8+ and PHP 8+
composer require arkaitzgarro/elastic-apm-laravel

# Laravel 6+
composer require arkaitzgarro/elastic-apm-laravel:^3.0

# Laravel 5.5 - 5.8
composer require arkaitzgarro/elastic-apm-laravel:^2.0
```

Laravel's provider auto-discover should find the package ServiceProvider. Otherwise, add the ServiceProvider class to the providers array in `config/app.php`:

```
'providers' => [
    // ... more providers
    \AG\ElasticApmLaravel\ServiceProvider::class,
],
```

From here, we will take care of everything based on your configuration. The agent and the middleware will be registered, and transactions will be sent to Elastic.

Agent configuration
-------------------

[](#agent-configuration)

The underlying APM Agent may be configured using environment variables as of version 2.0 of this package. Place the `ELASTIC_APM_*` variables in your `.env` file or use any other appropriate means to make them available to your project.

Note that features of the Agent may not be documented here and you should refer to the `nipwaayoni/elastic-apm-php-agent` [project documentation](https://github.com/nipwaayoni/elastic-apm-php-agent/blob/master/docs/config.md) for the full feature set.

The following options are still supported by this package and will take precedence over their `ELASTIC_APM_*` counterparts if present.

VariableAlternativeDescriptionAPM\_ACTIVEELASTIC\_APM\_ENABLED`true` or `false` defaults to `true`. If `false`, the agent will collect, but not send, transaction data; span collection will also be disabled.APM\_APPNAMEELASTIC\_APM\_SERVICE\_NAMEName of the app as it will appear in APM. Invalid special characters will be replaced with a hyphen.APM\_APPVERSIONELASTIC\_APM\_SERVICE\_VERSIONVersion of the app as it will appear in APM.APM\_SERVERURLELASTIC\_APM\_SERVER\_URLURL to the APM intake service.APM\_SECRETTOKENELASTIC\_APM\_SECRET\_TOKENSecret token, if required.APM\_BACKTRACEDEPTHELASTIC\_APM\_STACK\_TRACE\_LIMITDefaults to `0` (unlimited). Depth of backtrace in query span.The `APM_*` variables listed above *may* be removed in a future release.

### Laravel Options

[](#laravel-options)

The following environment variables are supported in the default configuration:

VariableDescriptionAPM\_LOG\_LEVELLog level for the APM Agent package. Must be PSR-3 compliant. Defaults to `error`.APM\_ACTIVE\_CLI`true` or `false` defaults to `true`. If `false`, the agent will not collect or send transaction or span data for non-HTTP requests but HTTP requests will still follow ELASTIC\_APM\_ENABLED. When ELASTIC\_APM\_ENABLED is `false`, this will have no effect.APM\_USEROUTEURI`true` or `false` defaults to `true`. The default behavior is to record the URL as defined in your routes configuration. Set to `false` to record the requested URL, but keep in mind that this can result in excessive unique entries in APM.APM\_IGNORE\_PATTERNSIgnore specific routes or jobs by transaction name. Should be a regular expression, and will match multiple patterns via pipe `|` in the regex. Note that 4 backslashes should be used to match a single backslash. Example: `"/\/health-check|^OPTIONS |Foo\\\\Bar\\\\Job/"`APM\_QUERYLOG`true` or `false` defaults to 'true'. Set to `false` to completely disable query logging, or to `auto` if you would like to use the threshold feature.APM\_THRESHOLDQuery threshold in milliseconds, defaults to `200`. If a query takes longer then 200ms, we enable the query log. Make sure you set `APM_QUERYLOG=auto`.APM\_MAXTRACEITEMSDefaults to `1000`. Max number of child items displayed when viewing trace details.APM\_RENDERSOURCEDefaults to `false`. Include source code in query span.You may also publish the `elastic-apm-laravel.php` configuration file to change additional settings:

```
php artisan vendor:publish --tag=config
```

Once published, open the `config/elastic-apm-laravel.php` file and review the various settings.

Logging
-------

[](#logging)

The Monolog instance used by your Laravel application will be automatically given to the Agent for logging. The log level for the Agent package is independent of the log level for your Laravel application. This allows you to only include Agent messages when they are useful. Use the `APM_LOG_LEVEL` environment setting for this. The default log level for the agent package is `info`.

Collectors
----------

[](#collectors)

The default collectors typically listen on events to measure portions of the request such as framework loading, database queries, or jobs.

The SpanCollector in particular allows you to measure any section of your own code via the `ApmCollector` Facade:

```
use AG\ElasticApmLaravel\Facades\ApmCollector;

ApmCollector::startMeasure('my-custom-span', 'custom', 'measure', 'My custom span');

// do something amazing

ApmCollector::stopMeasure('my-custom-span');
```

To record an additional span around your job execution, you may include the provided [job middleware](https://laravel.com/docs/6.x/queues#job-middleware):

```
public function middleware()
{
    return [
        app(\AG\ElasticApmLaravel\Jobs\Middleware\RecordTransaction::class),
    ];
}
```

**Note** Job middleware is **not** run when a job is created with the `dispatchNow()` method. Spans explicitly created within the job will still be collected, but the overall job span will not be included.

### Add a collector for other events

[](#add-a-collector-for-other-events)

You can add extra collector(s) to listen to your own application events or Laravel events like `Illuminate\Mail\Events\MessageSending` for example. We created a base collector that already includes functionality to measure events, that you can extend from:

```
// app/Collectors/MailMessageCollector.php

namespace YourApp\Collectors;

use AG\ElasticApmLaravel\Contracts\DataCollector;
use AG\ElasticApmLaravel\Collectors\EventDataCollector;

use Illuminate\Mail\Events\MessageSending;
use Illuminate\Mail\Events\MessageSent;

class MailMessageCollector extends EventDataCollector implements DataCollector
{
    public function getName(): string
    {
        return 'mail-message-collector';
    }

    protected function registerEventListeners(): void
    {
        $this->app->events->listen(MessageSending::class, function (\Swift_Message $message) {
            $this->startMeasure(
                'mail #' . $message->getId(),
                'mail.delivery',
            );
        });

        $this->app->events->listen(MessageSent::class, function (\Swift_Message $message) {
            $this->stopMeasure('mail #' . $message->getId());
        });
    }
}
```

Don't forget to register your collector when the application starts:

```
// app/Providers/AppServiceProvider.php

use AG\ElasticApmLaravel\Facades\ApmCollector;

use YourApp\Collectors\MailMessageCollector;

public function boot()
{
    // ...
    ApmCollector::addCollector(MailMessageCollector::class);
}
```

Alternatively, you can now simply tag your collector in the container and it will be discovered. Note that the collector **must** be tagged before the `Agent` is first resolved from the container, normally in the `boot` method of your provider.

```
// app/Providers/AppServiceProvider.php

use YourApp\Collectors\MailMessageCollector;

public function boot()
{
    $this->app->tag(MailMessageCollector::class, \AG\ElasticApmLaravel\ServiceProvider::COLLECTOR_TAG);
}
```

**Note** Collecting events is subject to the `APM_MAXTRACEITEMS` setting. If your collector defers adding events until the request is complete, and the total event count exceeds the max trace items, a higher than expected number of your events may be dropped. You should make every effort to collect events at the point they occur during the request processing. Using the `EventDataCollector::startMeasure()` method will flag an event for collection even if the max trace items has been reached when the measure is stopped.

Distributed Tracing
-------------------

[](#distributed-tracing)

[Distributed tracing](https://www.elastic.co/guide/en/apm/get-started/current/distributed-tracing.html) allows you to associate transactions in your Laravel application with transactions in services your application consumes. For example, if your Laravel application calls REST resources as part of handling a request, the REST transaction details will appear within your application transaction in Elastic APM. You enable distributed tracing by including an appropriate header in the http request your application makes to another service. For example:

```
$request = new Request(
    'PUT',
    '/some/backend/resource',
    [
        'Content-Type' => 'application/json',
    ],
    json_encode(...)
);

$request = \AG\ElasticApmLaravel\Facades\ApmAgent::addTraceParentHeader($request);

$this->client->send($request);
```

If you are not dealing with a `RequestInterface` object, you can get the current transaction and use the [array or string methods](https://github.com/nipwaayoni/elastic-apm-php-agent/blob/master/docs/examples/distributed-tracing.md) to get the `traceparent`.

```
$transaction = ApmAgent::getCurrentTransaction();

$headerArray = $transaction->traceHeaderAsArray();
$headerString = $transaction->traceHeaderAsString();
```

Development
-----------

[](#development)

Get Composer. Follow the instructions defined on the official [Composer page](https://getcomposer.org/doc/00-intro.md), or if you are using `homebrew`, just run:

```
brew install composer
```

Install project dependencies:

```
composer install
```

Run the unit test suite:

```
php vendor/bin/codecept run
```

Please adhere to [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) and [Symfony](https://symfony.com/doc/current/contributing/code/standards.html) coding standard. Run the following commands before pushing your code:

```
php ./vendor/bin/php-cs-fixer fix
```

### Integrate with a running application

[](#integrate-with-a-running-application)

To be able to test your changes with a locally running application, use Composer's functionality to require packages from local paths. On your project, add a local repository, just make sure the path to `elastic-apm-laravel` folder is correct:

```
composer config repositories.local '{"type": "path", "url": "../elastic-apm-laravel"}' --file composer.json
```

Then install the package from the source:

```
composer require arkaitzgarro/elastic-apm-laravel:@dev --prefer-source
```

You should see a message indicating that the package has been installed as symlink:

```
- Installing arkaitzgarro/elastic-apm-laravel (dev-chore/branch-name): Symlinking from ../elastic-apm-laravel
```

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance42

Moderate activity, may be stable

Popularity15

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~0 days

Total

5

Last Release

469d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/603dd27385d8a142141f9f42bc6c36deb94fa65b06730ff101ba7603d54326b8?d=identicon)[davidmanassa](/maintainers/davidmanassa)

---

Top Contributors

[![arkaitzgarro](https://avatars.githubusercontent.com/u/1712467?v=4)](https://github.com/arkaitzgarro "arkaitzgarro (54 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (20 commits)")[![cykirsch](https://avatars.githubusercontent.com/u/8845299?v=4)](https://github.com/cykirsch "cykirsch (10 commits)")[![dstepe](https://avatars.githubusercontent.com/u/2804725?v=4)](https://github.com/dstepe "dstepe (10 commits)")[![countless-integers](https://avatars.githubusercontent.com/u/2060726?v=4)](https://github.com/countless-integers "countless-integers (9 commits)")[![davidmanassa](https://avatars.githubusercontent.com/u/5729667?v=4)](https://github.com/davidmanassa "davidmanassa (6 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (1 commits)")[![alignwebs](https://avatars.githubusercontent.com/u/7644807?v=4)](https://github.com/alignwebs "alignwebs (1 commits)")[![datpmwork](https://avatars.githubusercontent.com/u/9279315?v=4)](https://github.com/datpmwork "datpmwork (1 commits)")[![hubie](https://avatars.githubusercontent.com/u/1660512?v=4)](https://github.com/hubie "hubie (1 commits)")[![kvas-damian](https://avatars.githubusercontent.com/u/2725894?v=4)](https://github.com/kvas-damian "kvas-damian (1 commits)")[![afiqiqmal](https://avatars.githubusercontent.com/u/9051312?v=4)](https://github.com/afiqiqmal "afiqiqmal (1 commits)")

---

Tags

laravelapmelastic

###  Code Quality

TestsCodeception

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/davidmanassa-elastic-apm-laravel/health.svg)

```
[![Health](https://phpackages.com/badges/davidmanassa-elastic-apm-laravel/health.svg)](https://phpackages.com/packages/davidmanassa-elastic-apm-laravel)
```

###  Alternatives

[laravel/cashier

Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.

2.5k25.9M107](/packages/laravel-cashier)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[arkaitzgarro/elastic-apm-laravel

Laravel APM agent for Elastic v2 intake API

84433.6k](/packages/arkaitzgarro-elastic-apm-laravel)[yadahan/laravel-authentication-log

Laravel Authentication Log provides authentication logger and notification for Laravel.

416632.8k5](/packages/yadahan-laravel-authentication-log)[laravel/cashier-paddle

Cashier Paddle provides an expressive, fluent interface to Paddle's subscription billing services.

264778.4k3](/packages/laravel-cashier-paddle)[api-platform/laravel

API Platform support for Laravel

59126.4k6](/packages/api-platform-laravel)

PHPackages © 2026

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