Skip to content

Commit 3d7f056

Browse files
committed
Command monitoring example
1 parent 07b48fc commit 3d7f056

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

examples/command_logger.php

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
// phpcs:disable Squiz.Classes.ClassFileName.NoMatch
5+
6+
namespace MongoDB\Examples;
7+
8+
require '../vendor/autoload.php';
9+
10+
use MongoDB\Client;
11+
use MongoDB\Driver\Monitoring\CommandFailedEvent;
12+
use MongoDB\Driver\Monitoring\CommandStartedEvent;
13+
use MongoDB\Driver\Monitoring\CommandSubscriber;
14+
use MongoDB\Driver\Monitoring\CommandSucceededEvent;
15+
16+
use function fprintf;
17+
use function get_class;
18+
use function getenv;
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+
class CommandLogger implements CommandSubscriber
31+
{
32+
public function commandStarted(CommandStartedEvent $event): void
33+
{
34+
fprintf(STDERR, "%s command started\n", $event->getCommandName());
35+
36+
fprintf(STDERR, "command: %s\n", toJson($event->getCommand()));
37+
fprintf(STDERR, "\n");
38+
}
39+
40+
public function commandSucceeded(CommandSucceededEvent $event): void
41+
{
42+
fprintf(STDERR, "%s command succeeded\n", $event->getCommandName());
43+
fprintf(STDERR, "reply: %s\n", toJson($event->getReply()));
44+
fprintf(STDERR, "\n");
45+
}
46+
47+
public function commandFailed(CommandFailedEvent $event): void
48+
{
49+
fprintf(STDERR, "%s command failed\n", $event->getCommandName());
50+
fprintf(STDERR, "reply: %s\n", toJson($event->getReply()));
51+
52+
$exception = $event->getError();
53+
fprintf(STDERR, "exception: %s\n", get_class($exception));
54+
fprintf(STDERR, "exception.code: %d\n", $exception->getCode());
55+
fprintf(STDERR, "exception.message: %s\n", $exception->getMessage());
56+
fprintf(STDERR, "\n");
57+
}
58+
}
59+
// phpcs:enable
60+
61+
$client = new Client(getenv('MONGODB_URI') ?? null);
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+
printf("%s\n", toJSON($document));
83+
}

0 commit comments

Comments
 (0)