Nuevo en la versión 1.18.
Definición
Parámetros
$subscriber: MongoDB\Controlador\Monitoreo\Suscriptor- Un suscriptor de eventos de monitoreo para registrarse con este Cliente.
Errores/Excepciones
MongoDB\Exception\InvalidArgumentException para errores relacionados con el análisis de parámetros u opciones.
MongoDB\Driver\Exception\InvalidArgumentException si el suscriptor es un MongoDB\Driver\Monitoring\LogSubscriber, ya que los registradores solo se pueden registrar globalmente con MongoDB\Driver\Monitoring\addSubscriber.
Comportamiento
Si $subscriber ya está registrado con este Cliente, esta función no hará nada. Si $subscriber también está registrado globalmente, aún solo será notificado una vez de cada evento para este Cliente.
Ejemplo
Cree un MongoDB\Driver\Monitoring\CommandSubscriber que registre todos los eventos:
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, )); } }
El suscriptor podrá entonces registrarse en un Cliente:
$client = new MongoDB\Client(); $subscriber = new LogCommandSubscriber(STDERR); $client->addSubscriber($subscriber); $client->test->users->insertOne(['username' => 'alice']);
El código anterior escribirá lo siguiente en la salida 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}