Skip to content

Commit

Permalink
Trace Larvel cache actions (#35)
Browse files Browse the repository at this point in the history
* Added support for expoing Cache actions within X-Ray

* Update README.md

* Fixes for styleci
  • Loading branch information
aran112000 authored Feb 8, 2023
1 parent 6dd4867 commit 6273fd1
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ XRAY_ENABLED=false
- [x] Database queries
- [x] Queue jobs
- [x] Blade view render
- [x] Cache requests


## LICENSE
Expand Down
7 changes: 7 additions & 0 deletions config/xray.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@
*/
'framework' => env('XRAY_FRAMEWORK', true),

/*
|--------------------------------------------------------------------------
| Trace Cache
|--------------------------------------------------------------------------
*/
'cache' => env('XRAY_CACHE', true),

/*
|--------------------------------------------------------------------------
| AWS, only needed if "APISegmentSubmitter" submitter is chosen
Expand Down
43 changes: 43 additions & 0 deletions src/Collectors/CacheCollector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

declare(strict_types=1);

namespace Napp\Xray\Collectors;

use Illuminate\Cache\Events\CacheHit;
use Illuminate\Cache\Events\CacheMissed;
use Illuminate\Cache\Events\KeyForgotten;
use Illuminate\Cache\Events\KeyWritten;
use Illuminate\Redis\Events\CommandExecuted;

class CacheCollector extends EventsCollector
{
public function registerEventListeners(): void
{
$this->app->events->listen(CacheHit::class, function (CacheHit $cache) {
$this->handleQueryReport($cache->key, 'Cache hit');
});
$this->app->events->listen(CacheMissed::class, function (CacheMissed $cache) {
$this->handleQueryReport($cache->key, 'Cache miss');
});
$this->app->events->listen(KeyWritten::class, function (KeyWritten $cache) {
$this->handleQueryReport($cache->key, 'Cache set');
});
$this->app->events->listen(KeyForgotten::class, function (KeyForgotten $cache) {
$this->handleQueryReport($cache->key, 'Cache delete');
});
$this->app->events->listen(CommandExecuted::class, function (CommandExecuted $cache) {
$this->handleQueryReport($cache->command, 'Cache redis command executed');
});
}

protected function handleQueryReport(string $cacheKey, string $eventName): void
{
$backtrace = $this->getBacktrace();
$this
->addSegment($eventName . ' at ' . $this->getCallerClass($backtrace))
->addAnnotation('Key', $cacheKey)
->addMetadata('backtrace', $backtrace)
->end();
}
}

0 comments on commit 6273fd1

Please sign in to comment.