MongoDB\Client::addSubscriber()
New in version 1.18.
Definition
Parameters
$subscriber
: MongoDB\Driver\Monitoring\Subscriber- A monitoring event subscriber to register with this Client.
Errors/Exceptions
MongoDB\Exception\InvalidArgumentException
for errors related to
the parsing of parameters or options.
MongoDB\Driver\Exception\InvalidArgumentException if subscriber is a MongoDB\Driver\Monitoring\LogSubscriber, since loggers can only be registered globally with MongoDB\Driver\Monitoring\addSubscriber.
Behavior
If $subscriber
is already registered with this Client, this function is a
no-op. If $subscriber
is also registered globally, it will still only be
notified once of each event for this Client.
Example
Create a MongoDB\Driver\Monitoring\CommandSubscriber that logs all events:
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, )); } }
The subscriber can then be registered with a Client:
$client = new MongoDB\Client(); $subscriber = new LogCommandSubscriber(STDERR); $client->addSubscriber($subscriber); $client->test->users->insertOne(['username' => 'alice']);
The above code will write the following to stderr output:
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}