Skip to content

Instantly share code, notes, and snippets.

@FeBe95
Created April 21, 2023 09:04
Show Gist options
  • Save FeBe95/e6fcfd704799b0c17a02bce6ecd451ec to your computer and use it in GitHub Desktop.
Save FeBe95/e6fcfd704799b0c17a02bce6ecd451ec to your computer and use it in GitHub Desktop.
Inspecting Server-to-Server Requests in Laravel with Clockwork
<?php
namespace App\Listeners;
use Illuminate\Http\Client\Events\RequestSending;
use Illuminate\Http\Client\Events\ResponseReceived;
use Illuminate\Http\Client\Request;
class ClockworkLogger
{
/**
* Handle the given event.
*
* @param RequestSending|ResponseReceived $event
* @return void
*/
public function handle(RequestSending|ResponseReceived $event): void
{
// Clockwork will not be installed in production (as it is configured as a dev-dependency in composer)
if (!class_exists("\Clockwork\Clockwork")) {
return;
}
$type = "";
if ($event instanceof RequestSending) $type = "start";
if ($event instanceof ResponseReceived) $type = "end";
$short = $this->getText($event->request, "short");
$long = $this->getText($event->request, "long");
$data = $this->getData($type, $short);
/** @var \Clockwork\Clockwork $clockwork */
$clockwork = clock();
$clockwork->event($long, $data)->$type();
if ($type === "start") {
$clockwork->log("info", $long);
}
}
private function getText(Request $request, string $type = "method"): string
{
$method = $request->method();
$fullUrl = $request->url();
$uri = $request->toPsrRequest()->getUri();
$host = rtrim($uri->getHost(), "/");
$path = ltrim($uri->getPath(), "/");
return match($type) {
"method" => "$method",
"short" => "$method $host/$path",
"long" => "$fullUrl$path",
};
}
private function getData(string $type, string $name): array
{
return [
$type => microtime(true),
"color" => "purple",
"name" => $name,
];
}
}
<?php
namespace App\Providers;
use App\Listeners\ClockworkLogger;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Http\Client\Events\RequestSending;
use Illuminate\Http\Client\Events\ResponseReceived;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
RequestSending::class => [
ClockworkLogger::class
],
ResponseReceived::class => [
ClockworkLogger::class
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*
* @return bool
*/
public function shouldDiscoverEvents()
{
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment