문서 메뉴
문서 홈
/ / /
PHP 라이브러리 매뉴얼
/ /

MongoDB\Client::addSubscriber()

이 페이지의 내용

  • 정의
  • 매개변수
  • 오류/예외
  • 행동
  • 예제
  • 다음도 참조하세요.

버전 1.18에 추가 되었습니다.

MongoDB\Client::addSubscriber()

이 클라이언트에 모니터링 이벤트 구독자를 등록합니다. 구독자는 이 클라이언트에 대한 모든 이벤트에 대한 알림을 받게 됩니다.

function addSubscriber(MongoDB\Driver\Monitoring\Subscriber $subscriber): void
$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 생성 모든 이벤트를 기록합니다.

<?php
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,
));
}
}

그런 다음 구독자는 클라이언트에 등록할 수 있습니다.

<?php
$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}

돌아가기

__get()