Skip to content
Snippets Groups Projects

Issue #3205503: Create a session count metric

1 file
+ 83
0
Compare changes
  • Side-by-side
  • Inline
<?php
namespace Drupal\prometheus_exporter\Plugin\MetricsCollector;
use Drupal\Core\Database\Connection;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\prometheus_exporter\Plugin\BaseMetricsCollector;
use PNX\Prometheus\Gauge;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Collects metrics for the number of sessions.
*
* @MetricsCollector(
* id = "session_count",
* title = @Translation("Session count"),
* description = @Translation("Provides metrics for the number of sessions.")
* )
*/
class SessionCountCollector extends BaseMetricsCollector implements ContainerFactoryPluginInterface {
/**
* The PDO database connection.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* SessionCountCollector constructor.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Database\Connection $connection
* The PDO database connection.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, Connection $connection) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->connection = $connection;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('database')
);
}
/**
* {@inheritdoc}
*/
public function collectMetrics() {
$gauge = new Gauge($this->getNamespace(), 'total', $this->getDescription());
foreach ($this->query() as $userType => $count) {
$gauge->set($count, ['user' => $userType]);
}
$metrics[] = $gauge;
return $metrics;
}
/**
* Query the session table to retrieve the number of sessions.
*
* @return array
* Count of sessions for anonymous and authenticated users.
*/
protected function query() {
return [
'anonymous' => (int) $this->connection->query('SELECT COUNT(1) FROM sessions WHERE uid = :anonymous', [':anonymous' => 0])->fetchField(),
'authenticated' => (int) $this->connection->query('SELECT COUNT(1) FROM sessions WHERE uid > :anonymous', [':anonymous' => 0])->fetchField(),
];
}
}
Loading