PHPackages                             code-distortion/clarity-context - 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. code-distortion/clarity-context

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

code-distortion/clarity-context
===============================

A Context Tracker package for Laravel

0.1.1(1y ago)03.7k1MITPHPPHP 8.0.\* | 8.1.\* | 8.2.\* | 8.3.\* | 8.4.\*CI passing

Since Dec 31Pushed 1y ago1 watchersCompare

[ Source](https://github.com/code-distortion/clarity-context)[ Packagist](https://packagist.org/packages/code-distortion/clarity-context)[ Docs](https://github.com/code-distortion/clarity-context)[ RSS](/packages/code-distortion-clarity-context/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (6)Versions (3)Used By (1)

Clarity Context - Understand Your Exceptions
============================================

[](#clarity-context---understand-your-exceptions)

[![Latest Version on Packagist](https://camo.githubusercontent.com/654df0bbe062ff6f49b2121aa11ee3350965d1ad2c45696841ec28072a2144e7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636f64652d646973746f7274696f6e2f636c61726974792d636f6e746578742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/code-distortion/clarity-context)[![PHP Version](https://camo.githubusercontent.com/17c04f775ccf1006bd98aaeda77764eb79a06963000af1655a02b85e1d8b77b2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e30253230746f253230382e342d626c75653f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/17c04f775ccf1006bd98aaeda77764eb79a06963000af1655a02b85e1d8b77b2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e30253230746f253230382e342d626c75653f7374796c653d666c61742d737175617265)[![Laravel](https://camo.githubusercontent.com/e0e6c184723421a782cb4f9a8ba15749fc8a49e6c7483ec26acda4678f2d1716/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d38253230746f25323031312d626c75653f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/e0e6c184723421a782cb4f9a8ba15749fc8a49e6c7483ec26acda4678f2d1716/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d38253230746f25323031312d626c75653f7374796c653d666c61742d737175617265)[![GitHub Workflow Status](https://camo.githubusercontent.com/d7db03e007e9f4721a26cf85fe111db17daeaa5c3cceed83b71996c42da79c41/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f636f64652d646973746f7274696f6e2f636c61726974792d636f6e746578742f72756e2d74657374732e796d6c3f6272616e63683d6d61696e267374796c653d666c61742d737175617265)](https://github.com/code-distortion/clarity-context/actions)[![Buy The World a Tree](https://camo.githubusercontent.com/dc3f77a9b22c3bc83c7b7d863bf138a7ca3418f1826b0b16d073d0aa87c16bc4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74726565776172652d2546302539462538432542332d6c69676874677265656e3f7374796c653d666c61742d737175617265)](https://plant.treeware.earth/code-distortion/clarity-context)[![Contributor Covenant](https://camo.githubusercontent.com/902d296a65b2997bada7e7717fd929d9177f3bd95414cbb5ea2ed843c680f314/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f6e7472696275746f72253230636f76656e616e742d76322e3125323061646f707465642d6666363962342e7376673f7374796c653d666c61742d737175617265)](.github/CODE_OF_CONDUCT.md)

***code-distortion/clarity-context*** is a **Context Tracker** package for Laravel that gives you a birds-eye-view of what your code was doing when an exception occurs.

[Add context](#add-context-to-your-code) to your code. e.g.

```
// in a file in your project
Clarity::context('Performing checkout', ['user-id' => $userId, 'order-id' => $orderId]);
…
```

```
// in another file
Clarity::context('Sending payment request to gateway');
Clarity::context(['payment-gateway' => 'examplexyz.com', 'card-id' => $cardId, 'amount' => $amount]);
…
```

This information is collected so when an exception occurs, it can be used to [show what your code was doing](#exception-logging) at the time. e.g.

```
app/Domain/Checkout/PerformCheckoutAction.php on line 20 (method "submit")
- "Performing checkout"
- user-id = 5
- order-id = 123

app/Domain/Payments/MakePaymentAction.php on line 19 (method "handle") (last application frame)
- "Sending payment request to gateway"
- payment-gateway = 'examplexyz.com'
- card-id = 456
- amount = '10.99'

vendor/laravel/framework/src/Illuminate/Http/Client/PendingRequest.php on line 856 (closure)
- The exception was thrown

```

Clarity Suite
-------------

[](#clarity-suite)

Clarity Context is a part of the ***Clarity Suite***, designed to let you manage exceptions more easily:

- **Clarity Context** - Understand Your Exceptions
- [Clarity Logger](https://github.com/code-distortion/clarity-logger) - Useful Exception Logs
- [Clarity Control](https://github.com/code-distortion/clarity-control) - Handle Your Exceptions

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
    - [Config File](#config-file)
- [Add Context to Your Code](#add-context-to-your-code)
- [Exception Logging](#exception-logging)

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

[](#installation)

Install the package via composer:

```
composer require code-distortion/clarity-context
```

### Config File

[](#config-file)

Use the following command if you would like to publish the `config/code_distortion.clarity_context.php` config file.

It simply gives you the option to turn this package on or off.

```
php artisan vendor:publish --provider="CodeDistortion\ClarityContext\ServiceProvider" --tag="config"
```

Add Context to Your Code
------------------------

[](#add-context-to-your-code)

Clarity Context lets you add context details throughout your code. It keeps track of what's currently in the call stack, ready for when an exception occurs. e.g.

```
Clarity::context("A quick description of what's currently happening");
Clarity::context(['some-relevant-id' => 123]);
```

You can add *strings* to explain what's currently happening in a sentence, or *associative arrays* to show specific details about what your code is currently working with.

Add context throughout your code in relevant places. Pick places that will give you the most insight when tracking down a problem. Add as many as you feel necessary.

You can pass multiple values at once:

```
Clarity::context("Processing csv file", ['file' => $file, 'category' => $categoryId]);
```

> ***Note:*** Don't add sensitive details that you don't want to be logged!

If you use trace identifiers to identify requests, you can add these as well. A good place to add them would be in a [service provider](https://laravel.com/docs/10.x/providers) or [request middleware](https://laravel.com/docs/10.x/middleware).

```
Clarity::traceIdentifier($traceId);
```

Exception Logging
-----------------

[](#exception-logging)

To log your exceptions, install a package like [Clarity Logger](https://github.com/code-distortion/clarity-logger) that's aware of *Clarity Context*. Follow its installation instructions to add logging to your project.

*Clarity Logger* will automatically include your context details alongside the details it normally logs. e.g.

```
EXCEPTION (UNCAUGHT):

exception     Illuminate\Http\Client\ConnectionException: "cURL error 6: Could not resolve host: api.example-gateway.com (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://api.example-gateway.com"
- location    app/Http/Controllers/CheckoutController.php on line 50 (method "submit")
- vendor      vendor/laravel/framework/src/Illuminate/Http/Client/PendingRequest.php on line 856 (closure)
request       POST https://my-website.com/checkout
- referrer    https://my-website.com/checkout
- route       cart.checkout
- middleware  web
- action      CheckoutController@submit
- trace-id    1234567890
user          3342 - Bob - bob@example.com (123.123.123.123)
- agent       Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36
date/time     Sunday 2nd April at 7:08pm (Australia/Sydney)  2023-04-02 19:08:23 AEST +10:00

CONTEXT:

app/Domain/Checkout/PerformCheckoutAction.php on line 20 (method "handle")
- "Performing checkout"
- user-id = 5
- order-id = 123

app/Domain/Payments/MakePaymentAction.php on line 19 (method "handle") (last application frame)
- "Sending payment request to gateway"
- payment-gateway = 'examplexyz.com'
- card-id = 456
- amount = '10.99'

vendor/laravel/framework/src/Illuminate/Http/Client/PendingRequest.php on line 856 (closure)
- The exception was thrown

```

⚙️ Click for more information.Logging Exceptions (Advanced)
-----------------------------

[](#logging-exceptions-advanced)

Clarity Context collects and manages the context details you've added to your code.

When an exception occurs, it builds a `CodeDistortion\ClarityContext\Context` object that can be used by the code doing the logging. This `Context` object contains the details you added (that were present in the call stack at the time).

If you'd like to handle the logging yourself, or are building a package to do so - this involves updating Laravel's [exception handler](https://laravel.com/docs/10.x/errors#the-exception-handler) `app/Exceptions/Handler.php` to use these `Context` values.

This section explains how to use this `Context` class.

### Obtaining the Context Object

[](#obtaining-the-context-object)

Use `Clarity::getExceptionContext($e)` to access the `CodeDistortion\ClarityContext\Context` object built for that exception.

Then you can choose how to log the exception based on what's inside the `Context` object.

```
// app/Exceptions/Handler.php

namespace App\Exceptions;

use CodeDistortion\ClarityContext\Clarity; // getDefault();             // the default value that will be returned
$context->getTraceIdentifiers();    // the trace identifiers
$context->getKnown();               // "known" issues associated with the exception
$context->hasKnown();               // whether the exception has "known" issues or not
$context->getReport();              // whether to trigger Laravel's report() method or not
$context->getRethrow();             // whether to rethrow, a closure to resolve it, or an exception itself to throw
$context->detailsAreWorthListing(); // whether details (other than those you can get by looking at the exception alone) are available

$stackTrace = $context->getStackTrace(); // the stack trace frames (most recent at the start)
$callStack = $context->getCallStack();   // the same as the stack trace, but in reverse
```

#### Stack Trace / Call Stack, and Frames

[](#stack-trace--call-stack-and-frames)

You can retrieve details about the call stack frames using `$context->getStackTrace()` or `$context->getCallStack()`. They contain objects representing each frame.

`getStackTrace()` contains the frames in order from most recent to oldest. `getCallStack()` is the same, except ordered from oldest to newest.

They also contain the following methods to help you find particular frames and meta information.

```
$stackTrace = $context->getStackTrace(); // or $context->getCallStack();

$stackTrace->getLastApplicationFrame();      // get the last application (i.e. non-vendor) frame
$stackTrace->getLastApplicationFrameIndex(); // get the index of the last application frame
$stackTrace->getExceptionThrownFrame();      // get the frame that threw the exception
$stackTrace->getExceptionThrownFrameIndex(); // get the index of the frame that threw the exception
$stackTrace->getExceptionCaughtFrame();      // get the frame that caught the exception
$stackTrace->getExceptionCaughtFrameIndex(); // get the index of the frame that caught the exception
$stackTrace->getMeta();                      // get the Meta objects - these represent the context details, amongst others
$stackTrace->getGroupedMeta();               // get the Meta objects grouped together in MetaGroups - see below
```

They are iterable, allowing them to be looped through.

You can retrieve the following details from the Frame objects inside:

```
$stackTrace = $context->getStackTrace(); // or $context->getCallStack();

foreach ($stackTrace as $frame) {
    $frame->getFile();                // the path to the file containing the code being run
    $frame->getProjectFile();         // the same file, but relative to the project-root's dir
    $frame->getLine();                // the relevant line number
    $frame->getFunction();            // the function or method being run at the time
    $frame->getClass();               // the class being used at the time
    $frame->getObject();              // the object instance being used at the time
    $frame->getType();                // the "type" ("::", "->")
    $frame->getArgs();                // the arguments the function or method was called with
    $frame->getMeta();                // retrieve the Meta objects, see below
    $frame->isApplicationFrame();     // is this an application (i.e. non-vendor) frame?
    $frame->isLastApplicationFrame(); // is this the last application frame (before the exception was thrown)?
    $frame->isVendorFrame();          // is this a vendor frame?
    $frame->isLastFrame();            // is this in the last frame in the (where the exception was thown)?
    $frame->exceptionWasThrownHere(); // was the exception thrown by this frame?
    $frame->exceptionWasCaughtHere(); // was the exception caught by this frame?
}
```

> ***Note:*** Some of the methods like `getFunction()`, `getClass()`, `getObject()` won't always return a value. It depends on the circumstance. See [PHP's debug\_backtrace method](https://www.php.net/manual/en/function.debug-backtrace.php) for more details.

#### Meta Objects

[](#meta-objects)

There are 5 types of Meta objects:

- `ContextMeta` - when the application called `Clarity::context(…)` to add context details,
- `CallMeta` - when the Control package ran some code for the application (e.g. using `Control::run()`),
- `LastApplicationFrameMeta` - the location of the last application (i.e. non-vendor) frame,
- `ExceptionThrownMeta` - the location the exception was thrown,
- `ExceptionCaughtMeta` - the location the exception was caught.

You can retrieve the following details from the Meta objects:

```
// all Meta classes
$meta->getFile();        // the relevant file
$meta->getProjectFile(); // the same file, but relative to the project-root's dir
$meta->getLine();        // the relevant line number
$meta->getFunction();    // the function or method being run at the time
$meta->getClass();       // the class being used at the time
$meta->getType();        // the "type" ("::", "->")
// ContextMeta only
$meta->getContext();     // the context array or sentence
// CallMeta only
$meta->wasCaughtHere();  // whether the excepton was caught here or not
$meta->getKnown();       // the "known" issues associated to the exception
```

There are several ways of retrieving Meta objects:

```
$context->getStackTrace()->getMeta(); // all the Meta objects, in stack trace order
$context->getCallStack()->getMeta();  // all the Meta objects, in call stack order
$frame->getMeta();                    // the Meta objects present in a particular frame
$metaGroup->getMeta();                // related Meta objects, grouped togther (see below)
```

Each of these methods accepts a meta-class string, or several of them, which limit the result. e.g.

```
$context->getStackTrace()->getMeta(ContextMeta::class); // only ContextMeta objects will be returned
```

#### MetaGroup Objects

[](#metagroup-objects)

When reporting the exception details, it's useful to group the Meta objects together. `MetaGroup` objects provide a way of grouping the Meta objects in a logical way.

The Meta objects within are related, i.e. in the same frame and on near-by lines.

```
$context->getStackTrace()->getMetaGroups();
$context->getCallStack()->getMetaGroups();
```

Each MetaGroup contains similar details to the `Frame` object.

```
$metaGroup->getFile();                    // the path to the file containing the code being run
$metaGroup->getProjectFile();             // the same file, but relative to the project-root's dir
$metaGroup->getLine();                    // the relevant line number
$metaGroup->getFunction();                // the function or method being run at the time
$metaGroup->getClass();                   // the class being used at the time
$metaGroup->getType();                    // the "type" ("::", "->")
$metaGroup->getMeta();                    // the meta objects contained within
$metaGroup->isInApplicationFrame();       // is this in an application (i.e. non-vendor) frame?
$metaGroup->isInLastApplicationFrame();   // is this in the last application frame (before the exception was thrown)?
$metaGroup->isInVendorFrame();            // is this in a vendor frame?
$metaGroup->isInLastFrame();              // is this in the last frame (where the exception was thown)?
$metaGroup->exceptionThrownInThisFrame(); // is this in the frame the exception was thrown from?
$metaGroup->exceptionCaughtInThisFrame(); // is this in the frame the exception was caught in?

```

### Context Objects Without an Exception

[](#context-objects-without-an-exception)

You can generate a Context object arbitrarily, without needing an exception.

The Context object returned will contain the current context details, like it normally would.

```
$context = Clarity::buildContextHere();
```

Testing This Package
--------------------

[](#testing-this-package)

- Clone this package: `git clone https://github.com/code-distortion/clarity-context.git .`
- Run `composer install` to install dependencies
- Run the tests: `composer test`

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

### SemVer

[](#semver)

This library uses [SemVer 2.0.0](https://semver.org/) versioning. This means that changes to `X` indicate a breaking change: `0.0.X`, `0.X.y`, `X.y.z`. When this library changes to version 1.0.0, 2.0.0 and so forth, it doesn't indicate that it's necessarily a notable release, it simply indicates that the changes were breaking.

Treeware
--------

[](#treeware)

This package is [Treeware](https://treeware.earth). If you use it in production, then we ask that you [**buy the world a tree**](https://plant.treeware.earth/code-distortion/clarity-context) to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

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

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

### Code of Conduct

[](#code-of-conduct)

Please see [CODE\_OF\_CONDUCT](.github/CODE_OF_CONDUCT.md) for details.

### Security

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Tim Chandler](https://github.com/code-distortion)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance42

Moderate activity, may be stable

Popularity16

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

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

Total

2

Last Release

467d ago

PHP version history (2 changes)0.1.0PHP 8.0.\* | 8.1.\* | 8.2.\* | 8.3.\*

0.1.1PHP 8.0.\* | 8.1.\* | 8.2.\* | 8.3.\* | 8.4.\*

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/56794290?v=4)[Tim](/maintainers/code-distortion)[@code-distortion](https://github.com/code-distortion)

---

Top Contributors

[![code-distortion](https://avatars.githubusercontent.com/u/56794290?v=4)](https://github.com/code-distortion "code-distortion (2 commits)")

---

Tags

loglaravelexceptionerrorContextreportcatch

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/code-distortion-clarity-context/health.svg)

```
[![Health](https://phpackages.com/badges/code-distortion-clarity-context/health.svg)](https://phpackages.com/packages/code-distortion-clarity-context)
```

###  Alternatives

[guanguans/laravel-exception-notify

Monitor exception and report to the notification channels(Log、Mail、AnPush、Bark、Chanify、DingTalk、Discord、Gitter、GoogleChat、IGot、Lark、Mattermost、MicrosoftTeams、NowPush、Ntfy、Push、Pushback、PushBullet、PushDeer、PushMe、Pushover、PushPlus、QQ、RocketChat、ServerChan、ShowdocPush、SimplePush、Slack、Telegram、WeWork、WPush、XiZhi、YiFengChuanHua、ZohoCliq、ZohoCliqWebHook、Zulip).

14642.7k1](/packages/guanguans-laravel-exception-notify)[yaro/log-envelope

Laravel 5 email on error

4147.0k](/packages/yaro-log-envelope)[rigor789/airbrake-laravel

Laravel package for the Airbrake API, which supports Errbit

1636.5k](/packages/rigor789-airbrake-laravel)

PHPackages © 2026

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