<?php
declare(strict_types=1);
/**
* @author Maciej Kaczmarek <maciej.kaczmarek@autentika.pl>
*/
namespace Hitso\Bundle\CommonBundle\Monitor;
use Doctrine\DBAL\Logging\DebugStack;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
class SlowQueryLogger implements EventSubscriberInterface
{
/**
* @var string
*/
private $logPath;
/**
* @var bool
*/
private $debug;
/**
* @var bool
*/
private $registered = false;
/**
* @var DebugStack
*/
private $logger;
/**
* SlowQueryLogger constructor.
*
* @param string $logPath
* @param string $lockPath
* @param bool $debug
* @param DebugStack $logger
*/
public function __construct($logPath, $lockPath, $debug, DebugStack $logger = null)
{
$this->logger = $logger;
$this->logPath = $logPath;
$this->debug = $debug;
}
public function onRequest()
{
if (!$this->registered && !$this->debug && $this->logger && $this->logger->enabled) {
$this->registered = true;
register_shutdown_function(function () {
foreach ($this->logger->queries as $query) {
if ($query['executionMS'] > 0.2) {
$entry = [
'stamp' => time(),
'time' => round($query['executionMS'] * 1000),
'query' => $query['sql'],
'params' => $query['params'],
'errors' => false,
];
file_put_contents($this->logPath, base64_encode(serialize($entry)) . PHP_EOL, FILE_APPEND);
}
}
});
}
}
public function getSlowQueries()
{
if (!file_exists($this->logPath)) {
return [];
}
$logs = array_filter(file($this->logPath));
unlink($this->logPath);
$logs = array_map(
function ($entry) {
return unserialize(base64_decode($entry));
},
$logs
);
return array_filter($logs);
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => ['onRequest', 512],
];
}
}