Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix | Replace Listener For Terminatable Middleware #31

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ testbench.yaml
vendor
node_modules
.php-cs-fixer.cache
.phpunit.cache/
1 change: 1 addition & 0 deletions config/request-logger.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

// config for Bilfeldt/RequestLogger

return [
/*
|--------------------------------------------------------------------------
Expand Down
52 changes: 52 additions & 0 deletions src/ArrayLogger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

namespace Bilfeldt\RequestLogger;

use Bilfeldt\RequestLogger\Contracts\RequestLoggerInterface;
use Bilfeldt\RequestLogger\Traits\Loggable;
use Illuminate\Http\Request;

class ArrayLogger implements RequestLoggerInterface
{
use Loggable;

/**
* Logs
*
* @var array<string, mixed>
*/
protected array $logs = [];

/** @inheritDoc */
public function log(Request $request, $response, ?int $duration = null, ?int $memory = null): void
{
$this->logs[] = [
'uuid' => $request->getUniqueId(),
'correlation_id' => $this->truncateToLength($request->getCorrelationId()),
'client_request_id' => $this->truncateToLength($request->getClientRequestId()),
'ip' => $request->ip(),
'session' => $request->hasSession() ? $request->session()->getId() : null,
'middleware' => array_values(optional($request->route())->gatherMiddleware() ?? []),
'method' => $request->getMethod(),
'route' => $this->truncateToLength(optional($request->route())->getName() ?? optional($request->route())->uri()),
'path' => $this->truncateToLength($request->path()),
'status' => $response->getStatusCode(),
'headers' => $this->getFiltered($request->headers->all()) ?: null,
'payload' => $this->getFiltered($request->input()) ?: null,
'response_headers' => $this->getFiltered($response->headers->all()) ?: null,
'response_body' => $this->getLoggableResponseContent($response),
'duration' => $duration,
'memory' => round($memory / 1024 / 1024, 2),
];
}

/**
* Get logs
*
* @return array<string, mixed>
*/
public function getLogs(): array
{
return $this->logs;
}
}
26 changes: 0 additions & 26 deletions src/EventServiceProvider.php

This file was deleted.

33 changes: 16 additions & 17 deletions src/Listeners/LogRequest.php → src/LogHandler.php
Original file line number Diff line number Diff line change
@@ -1,35 +1,34 @@
<?php

namespace Bilfeldt\RequestLogger\Listeners;
namespace Bilfeldt\RequestLogger;

use Bilfeldt\RequestLogger\RequestLoggerFacade;
use Illuminate\Foundation\Http\Events\RequestHandled;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Jaybizzle\CrawlerDetect\CrawlerDetect;
use Symfony\Component\HttpFoundation\Response;

/**
* This class is highly inspired by the Laravel Telescope Request Watcher.
*
* @see https://github.com/laravel/telescope/blob/master/src/Watchers/RequestWatcher.php
*/
class LogRequest
class LogHandler
{
public function handle(RequestHandled $event)
/**
* Handle a request log
*
* @param \Illuminate\Http\Request $request
* @param \Symfony\Component\HttpFoundation\Response $response
* @return void
*/
public function __invoke(Request $request, Response $response)
{
$startTime = defined('LARAVEL_START') ? LARAVEL_START : $event->request->server('REQUEST_TIME_FLOAT');
$startTime = defined('LARAVEL_START') ? LARAVEL_START : $request->server('REQUEST_TIME_FLOAT');
$duration = $startTime ? floor((microtime(true) - $startTime) * 1000) : null;
$memory = memory_get_peak_usage(true);

if ($this->shouldLog($event->request, $event->response)) {
$event->request->enableLog();
if ($this->shouldLog($request, $response)) {
$request->enableLog();
}

foreach (array_unique($event->request->attributes->get('log', [])) as $driver) {
foreach (array_unique($request->attributes->get('log', [])) as $driver) {
RequestLoggerFacade::driver($driver)->log(
$event->request,
$event->response,
$request,
$response,
$duration,
$memory
);
Expand Down
75 changes: 2 additions & 73 deletions src/Models/RequestLog.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,19 @@

use Bilfeldt\RequestLogger\Contracts\RequestLoggerInterface;
use Bilfeldt\RequestLogger\Database\Factories\RequestLogFactory;
use Bilfeldt\RequestLogger\RequestLoggerFacade;
use Bilfeldt\RequestLogger\Traits\Loggable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\MassPrunable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str;
use Illuminate\View\View;

class RequestLog extends Model implements RequestLoggerInterface
{
use HasFactory;
use MassPrunable;
use Loggable;

/**
* The attributes that are mass assignable.
Expand Down Expand Up @@ -137,73 +133,6 @@ protected function getRequestTeam(Request $request): ?Model
return null;
}

protected function getLoggableResponseContent(\Symfony\Component\HttpFoundation\Response $response): array
{
$content = $response->getContent();

if (is_string($content)) {
if (is_array(json_decode($content, true)) &&
json_last_error() === JSON_ERROR_NONE) {
return $this->contentWithinLimits($content)
? $this->getFiltered(json_decode($content, true))
: ['Purged By bilfeldt/laravel-request-logger'];
}

if (Str::startsWith(strtolower($response->headers->get('Content-Type')), 'text/plain')) {
return $this->contentWithinLimits($content) ? [$content] : ['purge' => 'bilfeldt/laravel-request-logger'];
}
}

if ($response instanceof RedirectResponse) {
return ['redirect' => $response->getTargetUrl()];
}

if ($response instanceof Response && $response->getOriginalContent() instanceof View) {
return [
'view' => $response->getOriginalContent()->getPath(),
//'data' => $this->extractDataFromView($response->getOriginalContent()),
];
}

return ['html' => 'non-json'];
}

protected function contentWithinLimits(string $content): bool
{
return intdiv(mb_strlen($content), 1000) <= 64;
}

protected function getFiltered(array $data)
{
return $this->replaceParameters($data, RequestLoggerFacade::getFilters());
}

protected function replaceParameters(array $array, array $hidden, string $value = '********'): array
{
foreach ($hidden as $parameter) {
if (Arr::get($array, $parameter)) {
Arr::set($array, $parameter, '********');
}
}

return $array;
}

protected function truncateToLength(?string $string, int $length = 255): ?string
{
if (! $string) {
return $string;
}

$truncator = '...';

if (mb_strwidth($string, 'UTF-8') <= $length) {
return $string;
}

return Str::limit($string, $length - mb_strwidth($truncator, 'UTF-8'), $truncator);
}

protected static function newFactory()
{
return RequestLogFactory::new();
Expand Down
5 changes: 5 additions & 0 deletions src/RequestLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ public function createNullDriver(): NullLogger
return new NullLogger();
}

public function createArrayDriver(): ArrayLogger
{
return app()->make(ArrayLogger::class);
}

Comment on lines +32 to +36
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
public function createArrayDriver(): ArrayLogger
{
return app()->make(ArrayLogger::class);
}

I don't really wanna have the burden of maintaining an Array logger when I think that is only relevant in the context of tests.

public function createModelDriver(): RequestLoggerInterface
{
$model = config('request-logger.drivers.model.class');
Expand Down
6 changes: 4 additions & 2 deletions src/RequestLoggerServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ class RequestLoggerServiceProvider extends ServiceProvider
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/request-logger.php', 'request-logger');

$this->app->register(EventServiceProvider::class);
}

/**
Expand All @@ -40,9 +38,13 @@ public function boot()
]);
}

$this->app->terminating(new LogHandler);

$this->registerMiddlewareAlias();
$this->bootMacros();

$this->app->scoped(ArrayLogger::class);

// TODO: Register command PruneRequestLogsCommand::class);
// TODO: Register EventServiceProvider::class
}
Expand Down
80 changes: 80 additions & 0 deletions src/Traits/Loggable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

namespace Bilfeldt\RequestLogger\Traits;

use Bilfeldt\RequestLogger\RequestLoggerFacade;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\View\View;

trait Loggable
{
protected function getLoggableResponseContent(\Symfony\Component\HttpFoundation\Response $response): array
{
$content = $response->getContent();

if (is_string($content)) {
if (is_array(json_decode($content, true)) &&
json_last_error() === JSON_ERROR_NONE) {
return $this->contentWithinLimits($content)
? $this->getFiltered(json_decode($content, true))
: ['Purged By bilfeldt/laravel-request-logger'];
}

if (Str::startsWith(strtolower($response->headers->get('Content-Type')), 'text/plain')) {
return $this->contentWithinLimits($content) ? [$content] : ['purge' => 'bilfeldt/laravel-request-logger'];
}
}

if ($response instanceof RedirectResponse) {
return ['redirect' => $response->getTargetUrl()];
}

if ($response instanceof Response && $response->getOriginalContent() instanceof View) {
return [
'view' => $response->getOriginalContent()->getPath(),
//'data' => $this->extractDataFromView($response->getOriginalContent()),
];
}

return ['html' => 'non-json'];
}

protected function contentWithinLimits(string $content): bool
{
return intdiv(mb_strlen($content), 1000) <= 64;
}

protected function getFiltered(array $data)
{
return $this->replaceParameters($data, RequestLoggerFacade::getFilters());
}

protected function replaceParameters(array $array, array $hidden, string $value = '********'): array
{
foreach ($hidden as $parameter) {
if (Arr::get($array, $parameter)) {
Arr::set($array, $parameter, '********');
}
}

return $array;
}

protected function truncateToLength(?string $string, int $length = 255): ?string
{
if (! $string) {
return $string;
}

$truncator = '...';

if (mb_strwidth($string, 'UTF-8') <= $length) {
return $string;
}

return Str::limit($string, $length - mb_strwidth($truncator, 'UTF-8'), $truncator);
}
}
Loading