PHPackages                             faustoff/laravel-contextify - 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. faustoff/laravel-contextify

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

faustoff/laravel-contextify
===========================

Contextual logging with inline notifications for Laravel.

4.4.0(2mo ago)61.3k↓33.3%[1 issues](https://github.com/faustoFF/laravel-contextify/issues)MITPHPPHP ^8.0CI passing

Since Jul 19Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/faustoFF/laravel-contextify)[ Packagist](https://packagist.org/packages/faustoff/laravel-contextify)[ RSS](/packages/faustoff-laravel-contextify/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (20)Versions (52)Used By (0)

[![Packagist Version](https://camo.githubusercontent.com/d10b9b6bdb6dc38137ea9074c5a3becbbd9b31f123b405246f360651deee0c4e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f66617573746f66662f6c61726176656c2d636f6e746578746966793f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/faustoff/laravel-contextify)[![Packagist Downloads](https://camo.githubusercontent.com/9c339cac545b5a1073b88fcf31cbefc96a0b26f1a386ff018c201144a4957ba4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f66617573746f66662f6c61726176656c2d636f6e746578746966793f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/faustoff/laravel-contextify)[![Packagist License](https://camo.githubusercontent.com/7e3289c128fdc135da549ff2011cfb151655ac6e4e41279bf66f418b30249210/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f66617573746f66662f6c61726176656c2d636f6e746578746966793f7374796c653d666f722d7468652d6261646765)](https://github.com/faustoff/laravel-contextify/blob/master/LICENSE)[![GitHub Repo stars](https://camo.githubusercontent.com/f8f0f73cc854a63e22c32ae6f1e2fd15fc84b91c8d9e744a4e7942d343b04194/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f66617573746f66662f6c61726176656c2d636f6e746578746966793f7374796c653d666f722d7468652d6261646765)](https://github.com/faustoff/laravel-contextify)

Laravel Contextify
==================

[](#laravel-contextify)

> **Contextual logging with inline notifications for Laravel.**

```
use Faustoff\Contextify\Facades\Contextify;

Contextify::notice('Order created', ['id' => $id])->notify(['mail']);
// [2025-01-01 12:00:00] production.NOTICE: Order created {"id":1} {"trace_id":"4f9c2a1b"}
```

**Laravel Contextify** enhances Laravel's logging with two main features:

1. **Inline Notifications** — [send notifications alongside logging](#sending-notifications) without splitting code into multiple lines for logging and notifying.
2. **Automatic Context Enrichment** — logs and notifications include extra contextual data from configured [Context Providers](#context-providers) (built-in: [Trace ID](src/Context/Providers/TraceIdContextProvider.php), [Process ID](src/Context/Providers/ProcessIdContextProvider.php), [Hostname](src/Context/Providers/HostnameContextProvider.php), [Call file and line](src/Context/Providers/CallContextProvider.php), and more), helping you keep messages short and clean by moving additional context out of the message itself into a separate area.

Provides [`Contextify`](src/Facades/Contextify.php) facade compatible with Laravel's [`Log`](https://laravel.com/docs/12.x/logging#writing-log-messages) facade: same methods (`debug`, `info`, `notice`, `warning`, `error`, `critical`, `alert`, `emergency`) with identical parameters, plus a chainable `notify()` method.

> **Name origin:** “Contextify” combines **Context** and **Notify**, reflecting its dual purpose — to enrich logs with contextual data and to send notifications for log events.

Features
--------

[](#features)

- 📧 [Notification Support](#sending-notifications): Send notifications via mail, telegram, or any Laravel notification channel
- 🔍 [Automatic Context Enrichment](#writing-logs): Logs and notifications automatically include extra contextual data from configured Context Providers
- 🔌 [Custom Context Providers](#creating-custom-context-providers): Extend built-in providers with your own
- 🔄 [Static &amp; Dynamic Providers](#static-context-providers): Static (cached) and dynamic (refreshed on each call) providers
- 🎯 [Group-Based Context](#group-based-context): Separate Context Providers for logs and notifications
- 📊 [PSR-3 Log Levels](#writing-logs): All standard log levels (debug, info, notice, warning, error, critical, alert, emergency)
- 🎨 [Custom Notifications](#sending-notifications): Extend notification classes and [add custom channels](#custom-notification-channels)
- 🔔 [Notifications Channel Filtering](#sending-notifications): Filter channels with `only` and `except` parameters
- 🔄 [Fluent API](#usage): Chain methods for readable code
- ⚡ [Monolog Integration](https://github.com/Seldaek/monolog/blob/main/doc/02-handlers-formatters-processors.md#processors): Integrates with Laravel's logging via Monolog processors

Requirements
------------

[](#requirements)

- PHP 8.0 or higher
- Laravel 8.0 or higher
- Monolog 2.0 or higher

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

[](#installation)

Install the package via Composer:

```
composer require faustoff/laravel-contextify
```

Configuration
-------------

[](#configuration)

Optionally, publish the configuration file:

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

This creates `config/contextify.php` for configuring [enable/disable](#environment-variables), [Context Providers](#context-providers) and [notifications](#notifications).

### Environment Variables

[](#environment-variables)

Add to `.env` to configure notification recipients and toggles:

```
CONTEXTIFY_ENABLED=true
CONTEXTIFY_NOTIFICATIONS_ENABLED=true
CONTEXTIFY_MAIL_ADDRESSES=admin@example.com,team@example.com
CONTEXTIFY_TELEGRAM_CHAT_ID=123456789
```

Set `CONTEXTIFY_ENABLED=false` to fully disable Contextify: no context providers are booted, the Monolog processor is not registered, exception reporting is not hooked, `notify()` calls are ignored, and `touch()` becomes a no-op. Logging methods (`debug`, `info`, etc.) still forward messages to Laravel's Log facade, but without any context enrichment. This is useful for disabling Contextify during testing to eliminate its influence on the code under test.

Set `CONTEXTIFY_NOTIFICATIONS_ENABLED=false` to disable all notifications (both inline `notify()` and automatic exception notifications).

> **Note:** `CONTEXTIFY_ENABLED` disables the entire package. `CONTEXTIFY_NOTIFICATIONS_ENABLED` only disables notifications while keeping context enrichment active.

> **Note:** Telegram notifications require the [laravel-notification-channels/telegram](https://github.com/laravel-notification-channels/telegram) package to be installed manually.

Usage
-----

[](#usage)

### Writing Logs

[](#writing-logs)

Use the [`Contextify`](src/Facades/Contextify.php) facade like Laravel's [`Log`](https://laravel.com/docs/12.x/logging#writing-log-messages) facade. Logs automatically include extra context from [Context Providers](#context-providers) configured [for logging](#group-based-context):

```
use Faustoff\Contextify\Facades\Contextify;

Contextify::debug('Debug message', ['key' => 'value']);
// [2025-01-01 12:00:00] local.DEBUG: Debug message {"key":"value"} {"pid":12345,"trace_id":"4f9c2a1bd3e7a8f0","file":"app/Services/ExampleService.php:42","class":"App\\Services\\ExampleService"}

Contextify::info('User logged in', ['user_id' => 123]);
// [2025-01-01 12:00:00] local.INFO: User logged in {"user_id":123} {"pid":12345,"trace_id":"4f9c2a1bd3e7a8f0","file":"app/Http/Controllers/Auth/LoginController.php:55","class":"App\\Http\\Controllers\\Auth\\LoginController"}

Contextify::notice('Important notice');
// [2025-01-01 12:00:00] local.NOTICE: Important notice  {"pid":12345,"trace_id":"4f9c2a1bd3e7a8f0","file":"routes/web.php:10","class":null}

// ... and the same for warning, error, critical, alert and emergency
```

### Sending Notifications

[](#sending-notifications)

Chain `notify()` after any [logging method](#writing-logs) to send notifications. Notifications include the log message, context, and extra context from [Context Providers](#context-providers) configured [for notifications](#group-based-context).

Filter channels using `only` and `except` parameters:

```
use Faustoff\Contextify\Facades\Contextify;

Contextify::error('Payment processing failed', ['order_id' => 456])->notify();
// [2025-01-01 12:00:00] local.ERROR: Payment processing failed {"order_id":456} {"pid":12345,"trace_id":"4f9c2a1bd3e7a8f0","file":"app/Http/Controllers/Api/OrderController.php:133","class":"App\\Http\\Controllers\\Api\\OrderController"}
// Notification with context {"order_id":456} and extra context sent to all configured notification channels

Contextify::critical('Database connection lost')->notify(only: ['mail']);
// [2025-01-01 12:00:00] local.CRITICAL: Database connection lost  {"pid":12345,"trace_id":"4f9c2a1bd3e7a8f0","file":"app/Console/Commands/MonitorCommand.php:71","class":"App\\Console\\Commands\\MonitorCommand"}
// Notification with extra context sent to a mail channel only

Contextify::alert('Security breach detected')->notify(except: ['telegram']);
// [2025-01-01 12:00:00] local.ALERT: Security breach detected  {"pid":12345,"trace_id":"4f9c2a1bd3e7a8f0","file":"app/Providers/AppServiceProvider.php:25","class":"App\\Providers\\AppServiceProvider"}
// Notification with extra context sent to all configured notification channels except a Telegram channel
```

Control notification sending conditionally using the `shouldNotify` parameter:

```
use Illuminate\Support\Facades\App;
use Faustoff\Contextify\Facades\Contextify;

Contextify::error('Payment processing failed')->notify(shouldNotify: App::isProduction());
```

If necessary, you can override the default implementation of the `LogNotification`:

```
namespace App\Notifications;

use Faustoff\Contextify\Notifications\LogNotification;

class CustomLogNotification extends LogNotification
{
    // Override methods as needed
}
```

Update configuration:

```
'notifications' => [
    'class' => \App\Notifications\CustomLogNotification::class,
],
```

### Exception Notifications

[](#exception-notifications)

Exceptions are automatically reported via notifications (enabled by default). Notifications include exception details (message and stack trace) and extra context from [Context Providers](#context-providers) configured [for notifications](#group-based-context).

If necessary, you can override the default implementation of the `ExceptionNotification`:

```
namespace App\Notifications;

use Faustoff\Contextify\Notifications\ExceptionNotification;

class CustomExceptionNotification extends ExceptionNotification
{
    // Override methods as needed
}
```

Update configuration:

```
'notifications' => [
    'exception_class' => \App\Notifications\CustomExceptionNotification::class,
],
```

To disable automatic exception notifications, set `reportable` to `null`:

```
'notifications' => [
    'reportable' => null,
],
```

> **Note:** `ExceptionNotificationFailedException` prevents infinite loops when exception notifications fail.

Context Providers
-----------------

[](#context-providers)

Context Providers add extra contextual data to logs and notifications, helping you keep log entry and notification messages short and clean by moving additional context out of the message itself into a separate context area. The contextual data is still present in the log entry or notification, but it's separated from the message itself—keeping the message focused while preserving all information for searching and analysis. You no longer need to worry about explicitly passing the required contextual data each time, as it will be added automatically.

### Static Context Providers

[](#static-context-providers)

Static providers return data that remains constant throughout the request/process lifecycle. They implement `StaticContextProviderInterface`.

Built-in:

- [ProcessIdContextProvider](src/Context/Providers/ProcessIdContextProvider.php): Adds the current PHP process ID (`pid`)
- [TraceIdContextProvider](src/Context/Providers/TraceIdContextProvider.php): Generates a unique 16-character hexadecimal trace ID (`trace_id`) for distributed tracing
- [HostnameContextProvider](src/Context/Providers/HostnameContextProvider.php): Adds the server hostname (`hostname`)
- [EnvironmentContextProvider](src/Context/Providers/EnvironmentContextProvider.php): Adds the application environment (`environment`)

#### Refreshing Static Context

[](#refreshing-static-context)

Static context is cached during application boot. Use `touch()` to refresh it manually, useful when a process is forked (e.g., queue workers) to generate a new trace ID:

```
use Faustoff\Contextify\Facades\Contextify;
use Faustoff\Contextify\Context\Providers\TraceIdContextProvider;

// Refresh specific provider (e.g., generate new trace ID)
Contextify::touch(TraceIdContextProvider::class);

// Refresh all static providers
Contextify::touch();
```

### Dynamic Context Providers

[](#dynamic-context-providers)

Dynamic providers refresh data on each log call. They implement `DynamicContextProviderInterface`.

Built-in:

- [CallContextProvider](src/Context/Providers/CallContextProvider.php): Adds the file path and line number (`file`) and class name (`class`) of the calling code
- [PeakMemoryUsageContextProvider](src/Context/Providers/PeakMemoryUsageContextProvider.php): Adds the peak memory usage in bytes (`peak_memory_usage`)
- [DateTimeContextProvider](src/Context/Providers/DateTimeContextProvider.php): Adds the current date and time in Laravel log format (`datetime`)

### Creating Custom Context Providers

[](#creating-custom-context-providers)

Implement `StaticContextProviderInterface` or `DynamicContextProviderInterface`:

```
namespace App\Context\Providers;

use Faustoff\Contextify\Context\Contracts\StaticContextProviderInterface;

class CustomContextProvider implements StaticContextProviderInterface
{
    public function getContext(): array
    {
        return [
            // implement ...
        ];
    }
}
```

### Registering Custom Providers

[](#registering-custom-providers)

Add custom providers to `config/contextify.php`:

```
use App\Context\Providers\CustomContextProvider;

return [
    'logs' => [
        'providers' => [
            // Built-in providers...

            // Custom providers
            CustomContextProvider::class,
        ],
    ],

    'notifications' => [
        'providers' => [
            // Built-in providers...

            // Custom providers
            CustomContextProvider::class,
        ],
    ],
];
```

### Group-Based Context

[](#group-based-context)

Define separate Context Providers for logs and notifications. If a provider appears in both sets, the same context data is used for both.

Configure in `config/contextify.php`:

- `logs.providers` — providers for log entries
- `notifications.providers` — providers for notifications

Example:

```
use Faustoff\Contextify\Context\Providers\CallContextProvider;
use Faustoff\Contextify\Context\Providers\EnvironmentContextProvider;
use Faustoff\Contextify\Context\Providers\TraceIdContextProvider;

return [
    'logs' => [
        'providers' => [
            TraceIdContextProvider::class,     // Shared
            CallContextProvider::class,        // Logs only
        ],
    ],

    'notifications' => [
        'providers' => [
            TraceIdContextProvider::class,     // Shared
            EnvironmentContextProvider::class, // Notifications only
        ],
    ],
];
```

Notifications
-------------

[](#notifications)

Supports **mail** and **telegram** channels out of the box. Mail works immediately; Telegram requires the [laravel-notification-channels/telegram](https://github.com/laravel-notification-channels/telegram) package.

### Configuration

[](#configuration-1)

Configure channels in `config/contextify.php`:

```
'notifications' => [
    'enabled' => env('CONTEXTIFY_NOTIFICATIONS_ENABLED', true),

    /*
     * Use associative array format ['channel' => 'queue'] to specify
     * queue per channel. Simple array ['channel'] uses 'default' queue.
     */
    'channels' => [
        'mail' => 'mail-queue',
        'telegram' => 'telegram-queue',
    ],

    'mail_addresses' => explode(',', env('CONTEXTIFY_MAIL_ADDRESSES', '')),

    'telegram_chat_id' => env('CONTEXTIFY_TELEGRAM_CHAT_ID'),
],
```

### Custom Notification Channels

[](#custom-notification-channels)

For example, to add [Slack notifications](https://laravel.com/docs/12.x/notifications#slack-notifications), you need to:

1. Create a custom notification class with a `toSlack()` method [implemented](https://laravel.com/docs/12.x/notifications#formatting-slack-notifications):

```
namespace App\Notifications;

use Faustoff\Contextify\Notifications\LogNotification;
use Illuminate\Notifications\Messages\SlackMessage;

class CustomLogNotification extends LogNotification
{
    public function toSlack($notifiable): SlackMessage
    {
        // See https://laravel.com/docs/12.x/notifications#formatting-slack-notifications

        return (new SlackMessage())
            ->content(ucfirst($this->level) . ': ' . $this->message);
    }
}
```

2. Create a custom notifiable class with a `routeNotificationForSlack()` method [implemented](https://laravel.com/docs/12.x/notifications#routing-slack-notifications):

```
namespace App\Notifications;

use Faustoff\Contextify\Notifications\Notifiable;

class CustomNotifiable extends Notifiable
{
    public function routeNotificationForSlack($notification): string
    {
        // See https://laravel.com/docs/12.x/notifications#routing-slack-notifications

        return config('services.slack.notifications.channel');
    }
}
```

3. [Configure Slack](https://laravel.com/docs/12.x/notifications#slack-prerequisites) in `config/services.php`.
4. Update `config/contextify.php`:

```
'notifications' => [
    'class' => \App\Notifications\CustomLogNotification::class,

    'notifiable' => \App\Notifications\CustomNotifiable::class,

    'channels' => [
        'mail',
        'telegram',
        'slack'
    ],
],
```

> **Note:** For exception notifications, extend `ExceptionNotification` and add the `toSlack()` method similarly.

Want more notification channels? You are welcome to [Laravel Notifications Channels](https://laravel-notification-channels.com/).

Console Commands
----------------

[](#console-commands)

### Tracking

[](#tracking)

Use `Faustoff\Contextify\Console\Trackable` trait to log command start, finish, and execution time:

```
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Faustoff\Contextify\Console\Trackable;
use Faustoff\Contextify\Facades\Contextify;

class SyncData extends Command
{
    use Trackable;

    protected $signature = 'data:sync';

    public function handle(): int
    {
        // Your business logic here

        Contextify::notice('Data was synced');

        return self::SUCCESS;
    }
}
```

Log:

```
[2025-01-01 12:00:00] local.DEBUG: Run with arguments {"command":"data:sync"} {"pid":12345,"trace_id":"4f9c2a1bd3e7a8f0","file":"app/Console/Commands/SyncData.php:42","class":"App\\Console\\Commands\\SyncData"}
[2025-01-01 12:00:00] local.NOTICE: Data was synced {"pid":12345,"trace_id":"4f9c2a1bd3e7a8f0","file":"app/Console/Commands/SyncData.php:42","class":"App\\Console\\Commands\\SyncData"}
[2025-01-01 12:00:00] local.DEBUG: Execution time: 1 second {"pid":12345,"trace_id":"4f9c2a1bd3e7a8f0","file":"app/Console/Commands/SyncData.php:42","class":"App\\Console\\Commands\\SyncData"}

```

### Output Capturing

[](#output-capturing)

Use `Faustoff\Contextify\Console\Outputable` trait to capture [Laravel console output](https://laravel.com/docs/12.x/artisan#writing-output) from `info()`-like methods and store it in logs:

```
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Faustoff\Contextify\Console\Outputable;

class SyncData extends Command
{
    use Outputable;

    protected $signature = 'data:sync';

    public function handle(): int
    {
        // You business logic here

        $this->info('Data was synced');

        return self::SUCCESS;
    }
}
```

Log:

```
[2025-01-01 12:00:00] local.NOTICE: Data was synced {"pid":12345,"trace_id":"4f9c2a1bd3e7a8f0","file":"app/Console/Commands/SyncData.php:42","class":"App\\Console\\Commands\\SyncData"}

```

### Handling Shutdown Signals

[](#handling-shutdown-signals)

Handle shutdown signals (`SIGQUIT`, `SIGINT`, `SIGTERM` by default) for graceful shutdown. Use the appropriate trait with `SignalableCommandInterface`:

- `TerminatableV62` for `symfony/console:shouldTerminate) {
                // Execution terminated by handle shutdown signal
                break;
            }
        }
    }
}
```

Log:

```
[2025-01-01 12:00:00] local.WARNING: Received SIGTERM (15) shutdown signal {"pid":12345,"trace_id":"4f9c2a1bd3e7a8f0","file":"app/Console/Commands/ConsumeStats.php:42","class":"App\\Console\\Commands\\ConsumeStats"}

```

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

Support
-------

[](#support)

For issues, questions, or contributions, please visit the [GitHub repository](https://github.com/faustoff/laravel-contextify).

###  Health Score

47

—

FairBetter than 94% of packages

Maintenance81

Actively maintained with recent releases

Popularity24

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity62

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

Recently: every ~14 days

Total

43

Last Release

79d ago

Major Versions

1.1.1 → 2.0.02024-03-10

2.7.3 → 3.0.02024-10-25

3.6.0 → v4.x-dev2025-12-03

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/653752?v=4)[faustoFF](/maintainers/faustoFF)[@faustoFF](https://github.com/faustoFF)

---

Top Contributors

[![faustoFF](https://avatars.githubusercontent.com/u/653752?v=4)](https://github.com/faustoFF "faustoFF (120 commits)")

---

Tags

contextlaravellognotify

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/faustoff-laravel-contextify/health.svg)

```
[![Health](https://phpackages.com/badges/faustoff-laravel-contextify/health.svg)](https://phpackages.com/packages/faustoff-laravel-contextify)
```

###  Alternatives

[laravel/cashier

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

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

Monitor the health of a Laravel application

86910.0M83](/packages/spatie-laravel-health)[yadahan/laravel-authentication-log

Laravel Authentication Log provides authentication logger and notification for Laravel.

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

The Illuminate Log package.

6224.3M518](/packages/illuminate-log)[inspector-apm/inspector-laravel

Code Execution Monitoring, built for developers.

2332.0M2](/packages/inspector-apm-inspector-laravel)[shaffe/laravel-mail-log-channel

A package to support logging via email in Laravel

1286.2k](/packages/shaffe-laravel-mail-log-channel)

PHPackages © 2026

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