BufferedPSRLogger   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 10
c 1
b 0
f 1
dl 0
loc 35
ccs 11
cts 11
cp 1
rs 10
wmc 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A flushTo() 0 9 1
A logQuery() 0 5 1
1
<?php
2
3
namespace mindplay\sql\framework;
4
5
use Psr\Log\LoggerInterface;
6
use Psr\Log\LogLevel;
7
8
/**
9
 * This class implements a buffered query logger.
10
 *
11
 * To flush recorded log-entries to a PSR-3 logger, call the `flushTo()` method, e.g. at
12
 * the end of an HTTP request.
13
 *
14
 * The queries are emitted in a `kodus/chrome-logger` compatible format.
15
 *
16
 * @link https://github.com/kodus/chrome-logger
17
 */
18
class BufferedPSRLogger implements Logger
19
{
20
    /**
21
     * @var array<string,mixed>[] buffered query log-entries
22
     */
23
    private array $entries = [];
24
25
    /**
26
     * Flush all recorded query log-entries to a single PSR-3 log-entry
27
     *
28
     * @param LoggerInterface $logger the PSR Logger to which the query-log will be flushed
29
     * @param string|mixed    $log_level PSR-3 log level (usually a string, defaults to "info")
30
     * @param string          $message   combined log entry title
31
     *
32
     * @see LogLevel
33
     */
34 1
    public function flushTo(LoggerInterface $logger, mixed $log_level = LogLevel::INFO, string $message = "INFO"): void
35
    {
36 1
        $logger->log(
37 1
            $log_level,
38 1
            $message,
39 1
            ["table: SQL Queries" => $this->entries]
40 1
        );
41
42 1
        $this->entries = [];
43
    }
44
45
    /**
46
     * @param array<string,mixed> $params
47
     */
48 1
    public function logQuery(string $sql, array $params, float $time_msec): void
49
    {
50 1
        $this->entries[] = [
51 1
            "time" => sprintf('%0.3f', $time_msec / 1000) . " s",
52 1
            "sql"  => QueryFormatter::formatQuery($sql, $params),
53 1
        ];
54
    }
55
}
56