Completed
Push — master ( 84095f...f0b462 )
by Rasmus
02:37
created

BufferedPSRLogger::flushTo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 3
crap 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 PSR-3 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
22
     */
23
    private $entries = [];
24
25
    /**
26
     * Flush all recorded query log-entries as 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 (defaults to INFO)
30
     * @param string          $message   combined log entry title
31
     *
32
     * @see LogLevel
33
     */
34 1
    public function flushTo(LoggerInterface $logger, $log_level = LogLevel::INFO, $message = "INFO")
35
    {
36 1
        $logger->log(
37
            $log_level,
38
            $message,
39 1
            ["table: SQL Queries" => $this->entries]
40
        );
41
42 1
        $this->entries = [];
43 1
    }
44
45 1
    public function logQuery($sql, $params, $time_msec)
46
    {
47 1
        $this->entries[] = [
48 1
            "time" => sprintf('%0.3f', $time_msec / 1000) . " s",
49 1
            "sql"  => QueryFormatter::formatQuery($sql, $params),
50
        ];
51 1
    }
52
}
53