1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Facile\MongoDbBundle\Services\Loggers; |
6
|
|
|
|
7
|
|
|
use Facile\MongoDbBundle\Services\Loggers\Model\LogEvent; |
8
|
|
|
use Symfony\Component\Stopwatch\Stopwatch; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class MongoLogger |
12
|
|
|
*/ |
13
|
|
|
class MongoLogger implements DataCollectorLoggerInterface |
14
|
|
|
{ |
15
|
|
|
/** @var \SplQueue|LogEvent[] */ |
16
|
|
|
private $logs; |
17
|
|
|
|
18
|
|
|
/** @var array|string[] */ |
19
|
|
|
private $connections; |
20
|
|
|
|
21
|
|
|
/** @var Stopwatch */ |
22
|
|
|
private $stopwatch; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* MongoLogger constructor. |
26
|
|
|
* |
27
|
|
|
* @param Stopwatch $stopwatch |
28
|
|
|
*/ |
29
|
6 |
|
public function __construct(Stopwatch $stopwatch) |
30
|
|
|
{ |
31
|
6 |
|
$this->logs = new \SplQueue(); |
32
|
6 |
|
$this->connections = []; |
33
|
6 |
|
$this->stopwatch = $stopwatch; |
34
|
6 |
|
} |
35
|
|
|
|
36
|
1 |
|
public function startLogging(LogEvent $event) |
37
|
|
|
{ |
38
|
1 |
|
$watchKey = uniqid('mongodb_query_log_'); |
39
|
1 |
|
$event->setWatchKey($watchKey); |
40
|
|
|
$this->stopwatch->start($watchKey); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
4 |
|
* @param string $connection |
45
|
|
|
*/ |
46
|
4 |
|
public function addConnection(string $connection) |
47
|
4 |
|
{ |
48
|
|
|
$this->connections[] = $connection; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
2 |
|
* @return array|\string[] |
53
|
|
|
*/ |
54
|
2 |
|
public function getConnections(): array |
55
|
|
|
{ |
56
|
|
|
return $this->connections; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
2 |
|
* @param LogEvent $event |
61
|
|
|
*/ |
62
|
2 |
|
public function logQuery(LogEvent $event) |
63
|
2 |
|
{ |
64
|
|
|
$watch = $this->stopwatch->stop($event->getWatchKey()); |
65
|
2 |
|
$event->setExecutionTime($watch->getDuration()); |
66
|
2 |
|
|
67
|
|
|
$this->logs->enqueue($event); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
2 |
|
* @return bool |
72
|
|
|
*/ |
73
|
2 |
|
public function hasLoggedEvents(): bool |
74
|
|
|
{ |
75
|
|
|
return !$this->logs->isEmpty(); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
2 |
|
* @return LogEvent |
80
|
|
|
*/ |
81
|
2 |
|
public function getLoggedEvent(): LogEvent |
82
|
1 |
|
{ |
83
|
|
|
if (!$this->hasLoggedEvents()) { |
84
|
|
|
throw new \LogicException('No more events logged!'); |
85
|
2 |
|
} |
86
|
|
|
|
87
|
|
|
return $this->logs->dequeue(); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|