Skip to content

Instantly share code, notes, and snippets.

@joelharkes
Created April 13, 2023 09:16
Show Gist options
  • Save joelharkes/fd2bb683897fc602a160960854028212 to your computer and use it in GitHub Desktop.
Save joelharkes/fd2bb683897fc602a160960854028212 to your computer and use it in GitHub Desktop.
Log Http server-to-server requests in Laravel Clockwork
<?php
declare(strict_types=1);
namespace App\Providers;
use Illuminate\Http\Client\Events\RequestSending;
use Illuminate\Http\Client\Events\ResponseReceived;
use Illuminate\Support\Facades\Event;
class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
public function boot()
{
Event::listen(function (RequestSending $event) {
$headersText = collect($event->request->headers())
->map(fn($values, $key) => $key . ": " . (is_array($values) ? implode(", ", $values) : $values))
->join("\r\n");
clock("{$event->request->method()} {$event->request->url()}\r\n{$headersText}\r\n\r\n{$event->request->body()}");
});
Event::listen(function (ResponseReceived $event) {
$headersText = collect($event->response->headers())
->map(fn($values, $key) => $key . ": " . (is_array($values) ? implode(", ", $values) : $values))
->join("\r\n");
$body = $event->response->body();
clock("{$event->response->status()} {$event->request->method()} {$event->request->url()}\r\n{$headersText}\r\n\r\n{$body}");
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment