Passed
Pull Request — master (#190)
by Arman
02:54
created

LoggerTrait   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 10
c 0
b 0
f 0
dl 0
loc 47
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A report() 0 3 1
A formatMessage() 0 8 3
1
<?php
2
3
/**
4
 * Quantum PHP Framework
5
 *
6
 * An open source software development framework for PHP
7
 *
8
 * @package Quantum
9
 * @author Arman Ag. <[email protected]>
10
 * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org)
11
 * @link http://quantum.softberg.org/
12
 * @since 2.9.5
13
 */
14
15
16
namespace Quantum\Libraries\Logger\Traits;
17
18
use Quantum\Libraries\Logger\Exceptions\LoggerException;
19
use Quantum\Libraries\Storage\FileSystem;
20
21
/**
22
 * Trait LoggerTrait
23
 * @package Quantum\Logger
24
 */
25
trait LoggerTrait
26
{
27
28
    /**
29
     * @var FileSystem
30
     */
31
    protected $fs;
32
33
    /**
34
     * @var string
35
     */
36
    protected $logFile;
37
38
    /**
39
     * Initialize the logger
40
     * @param array $params
41
     * @throws LoggerException
42
     */
43
    abstract protected function initialize(array $params): void;
44
45
    /**
46
     * Reports a log message
47
     * @param string $level
48
     * @param $message
49
     * @param array|null $context
50
     * @return void
51
     */
52
    public function report(string $level, $message, ?array $context = []): void
53
    {
54
        $this->fs->append($this->logFile, $this->formatMessage($level, $message, $context));
55
    }
56
57
    /**
58
     * Formats the log message
59
     * @param string $level
60
     * @param $message
61
     * @param array|null $context
62
     * @return string
63
     */
64
    protected function formatMessage(string $level, $message, ?array $context = []): string
65
    {
66
        return sprintf(
67
            "[%s] %s: %s%s",
68
            date('Y-m-d H:i:s'),
69
            ucfirst($level),
70
            is_array($message) ? json_encode($message, JSON_PRETTY_PRINT) : $message,
71
            isset($context['trace']) ? (PHP_EOL . $context['trace'] . PHP_EOL) : PHP_EOL
72
        );
73
    }
74
}