Skip to content

Commit 6dfc231

Browse files
committed
Command monitoring example
1 parent 3273248 commit 6dfc231

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

examples/command_logger.php

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace MongoDB\Examples;
5+
6+
require '../vendor/autoload.php';
7+
8+
use MongoDB\Client;
9+
use MongoDB\Driver\Monitoring\CommandFailedEvent;
10+
use MongoDB\Driver\Monitoring\CommandStartedEvent;
11+
use MongoDB\Driver\Monitoring\CommandSubscriber;
12+
use MongoDB\Driver\Monitoring\CommandSucceededEvent;
13+
14+
use function assert;
15+
use function fprintf;
16+
use function get_class;
17+
use function getenv;
18+
use function is_object;
19+
use function MongoDB\BSON\fromPHP;
20+
use function MongoDB\BSON\toRelaxedExtendedJSON;
21+
use function printf;
22+
23+
use const STDERR;
24+
25+
function toJSON(object $document): string
26+
{
27+
return toRelaxedExtendedJSON(fromPHP($document));
28+
}
29+
30+
// phpcs:disable Squiz.Classes.ClassFileName.NoMatch
31+
class CommandLogger implements CommandSubscriber
32+
{
33+
public function commandStarted(CommandStartedEvent $event): void
34+
{
35+
fprintf(STDERR, "%s command started\n", $event->getCommandName());
36+
37+
fprintf(STDERR, "command: %s\n", toJson($event->getCommand()));
38+
fprintf(STDERR, "\n");
39+
}
40+
41+
public function commandSucceeded(CommandSucceededEvent $event): void
42+
{
43+
fprintf(STDERR, "%s command succeeded\n", $event->getCommandName());
44+
fprintf(STDERR, "reply: %s\n", toJson($event->getReply()));
45+
fprintf(STDERR, "\n");
46+
}
47+
48+
public function commandFailed(CommandFailedEvent $event): void
49+
{
50+
fprintf(STDERR, "%s command failed\n", $event->getCommandName());
51+
fprintf(STDERR, "reply: %s\n", toJson($event->getReply()));
52+
53+
$exception = $event->getError();
54+
fprintf(STDERR, "exception: %s\n", get_class($exception));
55+
fprintf(STDERR, "exception.code: %d\n", $exception->getCode());
56+
fprintf(STDERR, "exception.message: %s\n", $exception->getMessage());
57+
fprintf(STDERR, "\n");
58+
}
59+
}
60+
61+
$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');
62+
63+
$client->getManager()->addSubscriber(new CommandLogger());
64+
65+
$collection = $client->test->coll;
66+
$collection->drop();
67+
68+
$collection->insertMany([
69+
['x' => 1],
70+
['x' => 2],
71+
['x' => 3],
72+
]);
73+
74+
$collection->updateMany(
75+
['x' => ['$gt' => 1]],
76+
['$set' => ['y' => 1]]
77+
);
78+
79+
$cursor = $collection->find([], ['batchSize' => 2]);
80+
81+
foreach ($cursor as $document) {
82+
assert(is_object($document));
83+
printf("%s\n", toJSON($document));
84+
}

0 commit comments

Comments
 (0)