MongoDB\Client::addSubscriber()
1.18版本新增。
定义
参数
$subscriber
: MongoDB\Driver\Monitoring\Subscriber- 向此客户端注册的监控事件订阅者。
错误/异常
MongoDB\Exception\InvalidArgumentException
用于与参数或选项解析相关的错误。
MongoDB\Driver\Exception\InvalidArgumentException 如果订阅者是 MongoDB\Driver\Monitoring\LogSubscriber ,因为记录器只能在全局范围内注册到 MongoDB\Driver\Monitoring\addSubscriber。
行为
如果$subscriber
已向此客户端注册,则此函数为空操作。 如果$subscriber
也已在全局注册,则该客户端的每个事件仍只会收到一次通知。
例子
创建 MongoDB\Driver\Monitoring\CommandSubscriber 记录所有事件:
use MongoDB\Driver\Monitoring\CommandSubscriber; use MongoDB\Driver\Monitoring\CommandStartedEvent; use MongoDB\Driver\Monitoring\CommandSucceededEvent; use MongoDB\Driver\Monitoring\CommandFailedEvent; class LogCommandSubscriber implements CommandSubscriber { private $stream; public function __construct($stream) { $this->stream = $stream; } public function commandStarted(CommandStartedEvent $event): void { fwrite($this->stream, sprintf( 'Started command #%d "%s": %s%s', $event->getRequestId(), $event->getCommandName(), Document::fromPHP($event->getCommand())->toCanonicalExtendedJSON(), PHP_EOL, )); } public function commandSucceeded(CommandSucceededEvent $event): void { fwrite($this->stream, sprintf( 'Succeeded command #%d "%s" in %d microseconds: %s%s', $event->getRequestId(), $event->getCommandName(), $event->getDurationMicros(), json_encode($event->getReply()), PHP_EOL, )); } public function commandFailed(CommandFailedEvent $event): void { fwrite($this->stream, sprintf( 'Failed command #%d "%s" in %d microseconds: %s%s', $event->getRequestId(), $event->getCommandName(), $event->getDurationMicros(), $event->getError()->getMessage(), PHP_EOL, )); } }
然后,订阅者可以在客户端注册:
$client = new MongoDB\Client(); $subscriber = new LogCommandSubscriber(STDERR); $client->addSubscriber($subscriber); $client->test->users->insertOne(['username' => 'alice']);
上述代码会将以下内容写入stderr 输出:
Started command #1 "insert": { "insert" : "users", "ordered" : true, "$db" : "test", "lsid" : { "id" : { "$binary" : { "base64" : "dKTBhZD7Qvi0vUhvR58mCA==", "subType" : "04" } } }, "documents" : [ { "username" : "alice", "_id" : { "$oid" : "655d1fca12e81018340a4fc2" } } ] } Succeeded command #1 "insert" in 876 microseconds: {"n":1,"ok":1}