Skip to content

Commit

Permalink
feat(cp): add cache support (#22)
Browse files Browse the repository at this point in the history
cherry-pick from Napp#35
  • Loading branch information
evan361425 authored Apr 21, 2023
1 parent e3df1cf commit cb422c7
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
7 changes: 7 additions & 0 deletions config/xray.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,13 @@
*/
'framework' => env('AWS_XRAY_ENABLE_FRAMEWORK', true),

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

/*
|--------------------------------------------------------------------------
| Sampled Rate If Not Receiving Header
Expand Down
42 changes: 42 additions & 0 deletions src/Collectors/CacheCollector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?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 Pkerrigan\Xray\Segment;

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');
});
}

protected function handleQueryReport(string $cacheKey, string $eventName): void
{
$backtrace = $this->getBacktrace();
$segment = (new Segment())->setName($eventName . ' at ' . $this->getCallerClass($backtrace));

$this
->addSegment($segment)
->addAnnotation('Key', $cacheKey)
->addMetadata('backtrace', $backtrace)
->end();
}
}
5 changes: 5 additions & 0 deletions src/XrayServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Napp\Xray;

use Illuminate\Support\ServiceProvider;
use Napp\Xray\Collectors\CacheCollector;
use Napp\Xray\Collectors\DatabaseQueryCollector;
use Napp\Xray\Collectors\FrameworkCollector;
use Napp\Xray\Collectors\JobCollector;
Expand Down Expand Up @@ -68,6 +69,10 @@ protected function registerCollectors(): void
if (config('xray.framework')) {
app(FrameworkCollector::class);
}

if (config('xray.cache')) {
app(CacheCollector::class);
}
}

/**
Expand Down

0 comments on commit cb422c7

Please sign in to comment.