From d06859cce3ecf01ae2d247fca2b2c53b147baa51 Mon Sep 17 00:00:00 2001 From: abdulmohsen Date: Sat, 11 Jun 2022 10:25:09 +0300 Subject: [PATCH] Added log levels to error object. --- src/Backends/Common/CommonTrait.php | 7 +++- src/Backends/Common/Error.php | 12 ++++++ src/Backends/Common/Levels.php | 59 +++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 src/Backends/Common/Levels.php diff --git a/src/Backends/Common/CommonTrait.php b/src/Backends/Common/CommonTrait.php index e8a17067..0bc49ff2 100644 --- a/src/Backends/Common/CommonTrait.php +++ b/src/Backends/Common/CommonTrait.php @@ -11,10 +11,11 @@ trait CommonTrait * * @param Context $context Context to associate the call with. * @param callable():Response $fn Closure + * @param string|null $action the action name to personalize the message. * * @return Response We should Expand the catch to include common http errors. json decode failing. */ - protected function tryResponse(Context $context, callable $fn): Response + protected function tryResponse(Context $context, callable $fn, string|null $action = null): Response { try { return $fn(); @@ -22,8 +23,9 @@ trait CommonTrait return new Response( status: false, error: new Error( - message: 'Unhandled exception was thrown in [%(client): %(backend)] context. %(message)', + message: 'Unhandled exception was thrown in [%(client): %(backend)] %(action). %(message)', context: [ + 'action' => $action ?? 'context', 'backend' => $context->backendName, 'client' => $context->clientName, 'message' => $e->getMessage(), @@ -34,6 +36,7 @@ trait CommonTrait 'message' => $e->getMessage(), ] ], + level: Levels::WARNING, previous: $e ) ); diff --git a/src/Backends/Common/Error.php b/src/Backends/Common/Error.php index 6d9a4c25..75f4c0ef 100644 --- a/src/Backends/Common/Error.php +++ b/src/Backends/Common/Error.php @@ -14,11 +14,13 @@ final class Error * * @param string $message Error message. * @param array $context Error message context. + * @param Levels $level Which log level the error should be logged into. * @param Throwable|null $previous Previous exception stack trace. */ public function __construct( public readonly string $message, public readonly array $context = [], + public readonly Levels $level = Levels::ERROR, public readonly Throwable|null $previous = null, ) { } @@ -43,6 +45,16 @@ final class Error return true === str_contains($this->message, '%('); } + /** + * Get which log level should this message be logged into. + * + * @return string + */ + public function level(): string + { + return $this->level->value; + } + /** * This method convert our logging messages into an actual human-readable message. * If no tags are found. we simply return the message as it is. diff --git a/src/Backends/Common/Levels.php b/src/Backends/Common/Levels.php new file mode 100644 index 00000000..1af12be5 --- /dev/null +++ b/src/Backends/Common/Levels.php @@ -0,0 +1,59 @@ +