Skip to content

Commit

Permalink
Only log event.duration if startTime is defined (#56)
Browse files Browse the repository at this point in the history
* Only log executionTimeNS if startTime can be deducted in middleware handle

* Update RequestLog.php

* Update LogRequest.php

* Update LogRequest.php

* Update RequestLog.php

* Update LogRequest.php

* Update LogRequest.php

* Update LogRequest.php

* Fix php-cs-fixer findings

* Don't set it to null

* LARAVEL_START constant

* Update LogRequest.php

---------

Co-authored-by: Mads Jon Nielsen <[email protected]>
  • Loading branch information
firecow and Mads Jon Nielsen authored Jul 8, 2024
1 parent 53d4dcc commit 7d01d7e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
11 changes: 7 additions & 4 deletions src/RequestLog/Data/RequestLog.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public function __construct(
public readonly array $responseCookies,
public readonly string $responseBody,
public ?Throwable $responseException,
public int $executionTimeNs,
public ?int $executionTimeNs,
) {
}

Expand Down Expand Up @@ -52,14 +52,17 @@ public function log()
],
'route' => $this->routeUri,
],
'event' => [
'duration' => $this->executionTimeNs, // In nanoseconds, see https://www.elastic.co/guide/en/ecs/current/ecs-event.html
],
'log' => [
'type' => 'request-logs',
],
];

if ($this->executionTimeNs !== null) {
$context['event'] = [
'duration' => $this->executionTimeNs, // In nanoseconds, see https://www.elastic.co/guide/en/ecs/current/ecs-event.html
];
}

if($this->responseException !== null) {
$message = $this->responseException->getMessage();
$message = empty($message) ? get_class($this->responseException) . ' thrown with empty message' : $message;
Expand Down
10 changes: 7 additions & 3 deletions src/RequestLog/Middleware/LogRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ class LogRequest
/**
* Holds the start time of the request
*
* @var int $startTime
* @var ?int $startTime
*/
protected $startTime;
protected $startTime = null;

/** Holds the request cookies. Some middleware will change the cookies, thus we need to save it from handle
*
Expand Down Expand Up @@ -103,7 +103,11 @@ private function logRequest(Request $request, Response $response): void
return;
}

$executionTimeNs = hrtime(true) - $this->startTime;
$executionTimeNs = null;

if ( ! is_null($this->startTime)) {
$executionTimeNs = hrtime(true) - $this->startTime;
}

$responseHeaders = $response->headers->all();
unset($responseHeaders['set-cookie']);
Expand Down

0 comments on commit 7d01d7e

Please sign in to comment.