Application Performance Monitoring (APM)

The MongoDB driver contains an event subscriber API, which allows applications to monitor commands and internal activity pertaining to the » Server Discovery and Monitoring Specification. This tutorial will demonstrate command monitoring using the MongoDB\Driver\Monitoring\CommandSubscriber interface.

The MongoDB\Driver\Monitoring\CommandSubscriber interface defines three methods: commandStarted, commandSucceeded, and commandFailed. Each of these three methods accept a single event argument of a specific class for the respective event. For example, the commandSucceeded's $event argument is a MongoDB\Driver\Monitoring\CommandSucceededEvent object.

In this tutorial we will implement a subscriber that creates a list of all the query profiles and the average time they took.

Subscriber Class Scaffolding

We start with the framework for our subscriber:

<?php

class QueryTimeCollector implements \MongoDB\Driver\Monitoring\CommandSubscriber
{
    public function 
commandStarted( \MongoDB\Driver\Monitoring\CommandStartedEvent $event )
    {
    }

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

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

?>

Registering the Subscriber

Once a subscriber object is instantiated, it needs to be registered with the driver's monitoring system. This is done by calling MongoDB\Driver\Monitoring\addSubscriber() or MongoDB\Driver\Manager::addSubscriber() to register the subscriber globally or with a specific Manager, respectively.

<?php

\MongoDB\Driver\Monitoring\addSubscriber( new QueryTimeCollector() );

?>

Implementing the Logic

With the object registered, the only thing left is to implement the logic in the subscriber class. To correlate the two events that make up a successfully executed command (commandStarted and commandSucceeded), each event object exposes a requestId field.

To record the average time per query shape, we will start by checking for a find command in the commandStarted event. We will then add an item to the pendingCommands property indexed by its requestId and with its value representing the query shape.

If we receive a corresponding commandSucceeded event with the same requestId, we add the duration of the event (from durationMicros) to the total time and increment the operation count.

If a corresponding commandFailed event is encountered, we just remove the entry from the pendingCommands property.

<?php

class QueryTimeCollector implements \MongoDB\Driver\Monitoring\CommandSubscriber
{
    private 
$pendingCommands = [];
    private 
$queryShapeStats = [];

    
/* Creates a query shape out of the filter argument. Right now it only
     * takes the top level fields into account */
    
private function createQueryShape( array $filter )
    {
        return 
json_encodearray_keys$filter ) );
    }

    public function 
commandStarted( \MongoDB\Driver\Monitoring\CommandStartedEvent $event )
    {
        if ( 
array_key_exists'find', (array) $event->getCommand() ) )
        {
            
$queryShape $this->createQueryShape( (array) $event->getCommand()->filter );
            
$this->pendingCommands[$event->getRequestId()] = $queryShape;
        }
    }

    public function 
commandSucceeded( \MongoDB\Driver\Monitoring\CommandSucceededEvent $event )
    {
        
$requestId $event->getRequestId();
        if ( 
array_key_exists$requestId$this->pendingCommands ) )
        {
            
$this->queryShapeStats[$this->pendingCommands[$requestId]]['count']++;
            
$this->queryShapeStats[$this->pendingCommands[$requestId]]['duration'] += $event->getDurationMicros();
            unset( 
$this->pendingCommands[$requestId] );
        }
    }

    public function 
commandFailed( \MongoDB\Driver\Monitoring\CommandFailedEvent $event )
    {
        if ( 
array_key_exists$event->getRequestId(), $this->pendingCommands ) )
        {
            unset( 
$this->pendingCommands[$event->getRequestId()] );
        }
    }

    public function 
__destruct()
    {
        foreach( 
$this->queryShapeStats as $shape => $stats )
        {
            echo 
"Shape: "$shape" ("$stats['count'], ")\n  ",
                
$stats['duration'] / $stats['count'], "µs\n\n";
        }
    }
}

$m = new \MongoDB\Driver\Manager'mongodb://localhost:27016' );

/* Add the subscriber */
\MongoDB\Driver\Monitoring\addSubscriber( new QueryTimeCollector() );

/* Do a bunch of queries */
$query = new \MongoDB\Driver\Query( [
    
'region_slug' => 'scotland-highlands''age' => [ '$gte' => 20 ]
] );
$cursor $m->executeQuery'dramio.whisky'$query );

$query = new \MongoDB\Driver\Query( [
    
'region_slug' => 'scotland-lowlands''age' => [ '$gte' => 15 ]
] );
$cursor $m->executeQuery'dramio.whisky'$query );

$query = new \MongoDB\Driver\Query( [ 'region_slug' => 'scotland-lowlands' ] );
$cursor $m->executeQuery'dramio.whisky'$query );

?>

Hier Kannst Du einen Kommentar verfassen


Bitte gib mindestens 10 Zeichen ein.
Wird geladen... Bitte warte.
* Pflichtangabe
Es sind noch keine Kommentare vorhanden.

PHP cURL-Tutorial: Verwendung von cURL zum Durchführen von HTTP-Anfragen

cURL ist eine leistungsstarke PHP-Erweiterung, die es Ihnen ermöglicht, mit verschiedenen Servern über verschiedene Protokolle wie HTTP, HTTPS, FTP und mehr zu kommunizieren. ...

TheMax

Autor : TheMax
Kategorie: PHP-Tutorials

Midjourney Tutorial - Anleitung für Anfänger

Über Midjourney, dem Tool zur Erstellung digitaler Bilder mithilfe von künstlicher Intelligenz, gibt es ein informatives Video mit dem Titel "Midjourney Tutorial auf Deutsch - Anleitung für Anfänger" ...

Mike94

Autor : Mike94
Kategorie: KI Tutorials

Grundlagen von Views in MySQL

Views in einer MySQL-Datenbank bieten die Möglichkeit, eine virtuelle Tabelle basierend auf dem Ergebnis einer SQL-Abfrage zu erstellen. ...

admin

Autor : admin
Kategorie: mySQL-Tutorials

Tutorial veröffentlichen

Tutorial veröffentlichen

Teile Dein Wissen mit anderen Entwicklern weltweit

Du bist Profi in deinem Bereich und möchtest dein Wissen teilen, dann melde dich jetzt an und teile es mit unserer PHP-Community

mehr erfahren

Tutorial veröffentlichen

Daten einer Abfrage mit Hilfe von Thumbnails nebeneinander ausgeben

Also den Fehler habe ich gefunden und abgestellt. Warum soll ich float meiden?

Geschrieben von Malchor am 17.05.2024 20:54:01
Forum: PHP Developer Forum
Daten einer Abfrage mit Hilfe von Thumbnails nebeneinander ausgeben

Dein HTML-Code ist definitiv kaputt und float solltest du auch vergessen. Beschäftige dich mit Flex-Box oder Grid

Geschrieben von scatello am 17.05.2024 20:43:50
Forum: PHP Developer Forum
Daten einer Abfrage mit Hilfe von Thumbnails nebeneinander ausgeben

Da ich viele unterschiedliche Tabellen benötige mache ich das so umständlich. Aber ist das der Grund warum das Floaten nicht funktioniert?

Geschrieben von Malchor am 17.05.2024 17:15:03
Forum: PHP Developer Forum
Daten einer Abfrage mit Hilfe von Thumbnails nebeneinander ausgeben

Du möchtest dir bestimmt mal ansehen, wie eine HTML-Tabelle richtig aufgebaut wird: https://www.w3schools.com/tags/tag_th.asp align solltest du ...

Geschrieben von scatello am 17.05.2024 17:12:34
Forum: PHP Developer Forum