> This page location: /docs.md > /docs/drivers.md > /docs/languages/php.md > /docs/php-library/current.md

> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# Monitor Application Events

## Overview

In this guide, you can learn how to set up and configure **monitoring** in the MongoDB PHP Library.

Monitoring is the process of gathering information about your application's behavior as it runs. This information can help you make informed decisions when designing and debugging your application. You can also use information from monitoring events to track your application's performance and resource use.

The MongoDB PHP Library emits command events and Server Discovery and Monitoring (SDAM) events that provide application information. You can listen for these events to monitor your application.

**Note:**

This page explains how to monitor your application in code. To learn how to record this information to an external log, see the [Log Driver Events](https://www.mongodb.com/docs/php-library/current/monitoring-logging/logging.md#std-label-php-logging) guide.

## Event Types

The type of event that the driver emits depends on the operation being performed. The following table describes the types of events that the driver emits:

| Event Type | Description |
| --- | --- |
| Command events | Events related to MongoDB database commands, such as `find`, `insert`, `delete`, and `count`. To learn how to use the PHP library to run a database command, see [Run a Database Command](https://www.mongodb.com/docs/php-library/current/run-command.md#std-label-php-run-command). For more information about MongoDB database commands, see [Database Commands](https://www.mongodb.com/docs/manual/reference/command/) in the MongoDB Server manual. |
| Server Discovery and Monitoring (SDAM) events | Events related to changes in the state of the MongoDB deployment. |

## Monitor Events

To monitor events, you must perform the following actions:

1. [Create an Event Subscriber](https://www.mongodb.com/docs/php-library/current/monitoring-logging/monitoring.md#std-label-php-subscribe): Create a class that implements the command or SDAM event subscriber

2. [Register an Event Subscriber](https://www.mongodb.com/docs/php-library/current/monitoring-logging/monitoring.md#std-label-php-register): Register a monitoring event subscriber with your `MongoDB\Client`

**Tip:**

To view a list of monitoring events to which you can subscribe, see the [Monitoring classes and subscriber functions](https://php.net/mongodb.monitoring) section of the PHP manual.

### Create an Event Subscriber

To subscribe to a monitoring event, create a class that implements the event subscriber interface. You can implement the following interfaces:

- `MongoDB\Driver\Monitoring\CommandSubscriber`, which subscribes to command events

- `MongoDB\Driver\Monitoring\SDAMSubscriber`, which subscribes to SDAM events

#### Command Event Subscriber Example

To subscribe to an SDAM event, create a class that implements the `MongoDB\Driver\Monitoring\CommandSubscriber` interface. In your class, define each of the `CommandSubscriber` methods. The following table describes these methods and the command events they receive notifications for:

| Method | Command Event | Description |
| --- | --- | --- |
| [commandFailed()](https://php.net/mongodb-driver-monitoring-commandsubscriber.commandfailed) | [CommandFailedEvent](https://php.net/class.mongodb-driver-monitoring-commandfailedevent) | Called when a command does not succeed |
| [commandStarted()](https://php.net/mongodb-driver-monitoring-commandsubscriber.commandstarted) | [CommandStartedEvent](https://php.net/class.mongodb-driver-monitoring-commandstartedevent) | Called when a command is sent to the server |
| [commandSucceeded()](https://php.net/mongodb-driver-monitoring-commandsubscriber.commandsucceeded) | [CommandSucceededEvent](https://php.net/class.mongodb-driver-monitoring-commandsucceededevent) | Called when a command succeeds |

The following code creates the `MyCommandSubscriber` class, which implements the `CommandSubscriber` interface. The class defines each `CommandSubscriber` method and includes custom logic for the `commandStarted()` method, which prints details about each new command that the server receives:

```php
class MyCommandSubscriber implements MongoDB\Driver\Monitoring\CommandSubscriber
{
    /** @param resource $stream */
    public function __construct(private $stream)
    {
    }

    public function commandStarted(MongoDB\Driver\Monitoring\CommandStartedEvent $event): void
    {
        fwrite($this->stream, sprintf(
            'Started command #%d "%s": %s%s',
            $event->getRequestId(),
            $event->getCommandName(),
            MongoDB\BSON\Document::fromPHP($event->getCommand())->toCanonicalExtendedJSON(),
            PHP_EOL,
        ));
    }

    public function commandSucceeded(MongoDB\Driver\Monitoring\CommandSucceededEvent $event): void
    {
    }

    public function commandFailed(MongoDB\Driver\Monitoring\CommandFailedEvent $event): void
    {
    }
}
```

#### SDAM Event Subscriber Example

To subscribe to an SDAM event, create a class that implements the `MongoDB\Driver\Monitoring\SDAMSubscriber` interface. In your class, define each `SDAMSubscriber` method. The following table describes these methods and the command events they receive notifications for:

| Method | SDAM Event | Description |
| --- | --- | --- |
| [serverChanged()](https://php.net/mongodb-driver-monitoring-sdamsubscriber.serverchanged) | [ServerChangedEvent](https://php.net/class.mongodb-driver-monitoring-serverchangedevent) | Called when a server's description changes |
| [serverClosed()](https://php.net/mongodb-driver-monitoring-sdamsubscriber.serverclosed) | [ServerClosedEvent](https://php.net/class.mongodb-driver-monitoring-serverclosedevent) | Called when a server is removed from the topology |
| [serverHeartbeatFailed()](https://php.net/mongodb-driver-monitoring-sdamsubscriber.serverheartbeatfailed) | [ServerHeartbeatFailedEvent](https://php.net/class.mongodb-driver-monitoring-serverheartbeatfailedevent) | Called when a server heartbeat is unsuccessful |
| [serverHeartbeatStarted()](https://php.net/mongodb-driver-monitoring-sdamsubscriber.serverheartbeatstarted) | [ServerHeartbeatStartedEvent](https://php.net/class.mongodb-driver-monitoring-serverheartbeatstartedevent) | Called when the server receives a heartbeat |
| [serverHeartbeatSucceeded()](https://php.net/mongodb-driver-monitoring-sdamsubscriber.serverheartbeatsucceeded) | [ServerHeartbeatSucceededEvent](https://php.net/class.mongodb-driver-monitoring-serverheartbeatsucceededevent) | Called when a server heartbeat succeeds |
| [serverOpening()](https://php.net/mongodb-driver-monitoring-sdamsubscriber.serveropening) | [ServerOpeningEvent](https://php.net/class.mongodb-driver-monitoring-serveropeningevent) | Called when a new server is added to the topology |
| [topologyChanged()](https://php.net/mongodb-driver-monitoring-sdamsubscriber.topologychanged) | [TopologyChangedEvent](https://php.net/class.mongodb-driver-monitoring-topologychangedevent) | Called when the topology description changes |
| [topologyClosed()](https://php.net/mongodb-driver-monitoring-sdamsubscriber.topologyclosed) | [TopologyClosedEvent](https://php.net/class.mongodb-driver-monitoring-topologyclosedevent) | Called when the topology is closed |
| [topologyOpening()](https://php.net/mongodb-driver-monitoring-sdamsubscriber.topologyopening) | [TopologyOpeningEvent](https://php.net/class.mongodb-driver-monitoring-topologyopeningevent) | Called when the topology is opened |

The following code creates the `MySDAMSubscriber` class, which implements the `SDAMSubscriber` interface. The class defines each `SDAMSubscriber` method and includes custom logic for the `serverOpening()` method, which prints details about servers added to the topology:

```php
class MySDAMSubscriber implements MongoDB\Driver\Monitoring\SDAMSubscriber
{
    /** @param resource $stream */
    public function __construct(private $stream)
    {
    }

    public function serverOpening(MongoDB\Driver\Monitoring\ServerOpeningEvent $event): void
    {
        fprintf(
            $this->stream,
            'Server opening on %s:%s\n',
            $event->getHost(),
            $event->getPort(),
            PHP_EOL,
        );
    }

    public function serverClosed(MongoDB\Driver\Monitoring\ServerClosedEvent $event): void
    {
    }

    public function serverChanged(MongoDB\Driver\Monitoring\ServerChangedEvent $event): void
    {
    }

    public function serverHeartbeatFailed(MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent $event): void
    {
    }

    public function serverHeartbeatStarted(MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent $event): void
    {
    }

    public function serverHeartbeatSucceeded(MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent $event): void
    {
    }

    public function topologyChanged(MongoDB\Driver\Monitoring\TopologyChangedEvent $event): void
    {
    }

    public function topologyClosed(MongoDB\Driver\Monitoring\TopologyClosedEvent $event): void
    {
    }

    public function topologyOpening(MongoDB\Driver\Monitoring\TopologyOpeningEvent $event): void
    {
    }
}
```

### Register an Event Subscriber

After creating a class that implements your subscriber interface, you must register this class with a `MongoDB\Client` to receive event notifications for your client. To register a subscriber, call the `MongoDB\Client::addSubscriber()` method and pass an instance of your subscriber class as a parameter.

#### Example

The following code registers the command and SDAM event subscribers created in the [Create an Event Subscriber](https://www.mongodb.com/docs/php-library/current/monitoring-logging/monitoring.md#std-label-php-subscribe) section of this page with a `MongoDB\Client`:

```php
$commandSub = new MyCommandSubscriber(STDERR);
$sdamSub = new MySDAMSubscriber(STDERR);

$client->addSubscriber($commandSub);
$client->addSubscriber($sdamSub);
```

When you start the application and run an insert command, your subscribers record the events and output messages that resemble the following:

```none
Server opening on ac-rmuag0v-shard-00-00.gh0qg50.mongodb.net:27017
Server opening on ac-rmuag0v-shard-00-01.gh0qg50.mongodb.net:27017
Server opening on ac-rmuag0v-shard-00-02.gh0qg50.mongodb.net:27017
Started command #3 "insert": { "insert" : ... }
```

## Remove a Subscriber

To unregister a subscriber from your client, use the `MongoDB\Client::removeSubscriber()` method.

The following code shows how to remove the subscriber created in the [Command Event Subscriber Example](https://www.mongodb.com/docs/php-library/current/monitoring-logging/monitoring.md#std-label-php-subscribe-command) section of this page:

```php
$client->removeSubscriber($commandSub);
```

## API Documentation

To learn more about any of the classes or methods discussed in this guide, see the following API documentation:

- [`MongoDB\Client::addSubscriber()`](https://www.mongodb.com/docs/php-library/current/reference/method/mongodbclient-addsubscriber.md#mongodb-phpmethod-phpmethod.MongoDB-Client--addSubscriber--)

- [`MongoDB\Client::removeSubscriber()`](https://www.mongodb.com/docs/php-library/current/reference/method/mongodbclient-removesubscriber.md#mongodb-phpmethod-phpmethod.MongoDB-Client--removeSubscriber--)

To learn more about subscriber classes and methods, see the following pages in the PHP manual:

- [MongoDB\Driver\Monitoring\CommandSubscriber](https://php.net/mongodb-driver-monitoring-commandsubscriber)

- [MongoDB\Driver\Monitoring\SDAMSubscriber](https://php.net/mongodb-driver-monitoring-sdamsubscriber)
