From c7617cbf6e9e3a5c5e29885241748e037ecf0684 Mon Sep 17 00:00:00 2001 From: Konstantin Grachev Date: Sat, 23 Jan 2021 00:36:45 +0300 Subject: [PATCH] Add logger --- composer.json | 3 ++- src/Connection.php | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 470c45b..5a514dc 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,8 @@ "ext-json": "*", "clue/socket-raw": "^1.5", "composer/semver": "^3.2", - "phpinnacle/buffer": "^1.2" + "phpinnacle/buffer": "^1.2", + "psr/log": "^1.1" }, "require-dev": { "ergebnis/composer-normalize": "9999999-dev", diff --git a/src/Connection.php b/src/Connection.php index f3233da..59f5f67 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -6,6 +6,8 @@ namespace Nsq; use Composer\InstalledVersions; use PHPinnacle\Buffer\ByteBuffer; +use Psr\Log\LoggerInterface; +use Psr\Log\NullLogger; use Socket\Raw\Factory; use Socket\Raw\Socket; use Throwable; @@ -35,6 +37,8 @@ abstract class Connection public ?Socket $socket = null; + protected LoggerInterface $logger; + private bool $closed = false; private Config $config; @@ -46,6 +50,7 @@ abstract class Connection public function __construct( string $address, + LoggerInterface $logger = null, string $clientId = null, string $hostname = null, string $userAgent = null @@ -57,6 +62,8 @@ abstract class Connection 'hostname' => $hostname ?? '', 'user_agent' => $userAgent ?? 'nsqphp/'.InstalledVersions::getPrettyVersion('nsq/nsq'), ]; + + $this->logger = $logger ?? new NullLogger(); } public function connect(): void @@ -67,6 +74,8 @@ abstract class Connection $body = json_encode($this->features, JSON_THROW_ON_ERROR | JSON_FORCE_OBJECT); $size = pack('N', \strlen($body)); + $this->logger->info('Feature Negotiation: '.http_build_query($this->features)); + $this->send('IDENTIFY '.PHP_EOL.$size.$body)->expectResponse(self::OK); } @@ -86,7 +95,7 @@ abstract class Connection $this->socket->close(); } } catch (Throwable $e) { - // Not interested + $this->logger->debug($e->getMessage(), ['exception' => $e]); } $this->closed = true; @@ -111,11 +120,15 @@ abstract class Connection { $socket = $this->socket(); + $this->logger->debug('Send buffer: '.$buffer); + try { $socket->write($buffer); } catch (Throwable $e) { $this->closed = true; + $this->logger->error($e->getMessage(), ['exception' => $e]); + throw $e; }