Test Failed
Push — master ( 21e806...ed25dd )
by Fran
05:25 queued 02:04
created

Logger::warningLog()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
3
namespace PSFS\base;
4
5
use Monolog\Formatter\LineFormatter;
6
use Monolog\Handler\FirePHPHandler;
7
use Monolog\Handler\StreamHandler;
8
use Monolog\Logger as Monolog;
9
use Monolog\Processor\MemoryUsageProcessor;
10
use Monolog\Processor\UidProcessor;
11
use PSFS\base\config\Config;
12
use PSFS\base\types\helpers\GeneratorHelper;
13
use PSFS\base\types\helpers\Inspector;
14
use PSFS\base\types\helpers\SlackHelper;
15
use PSFS\base\types\traits\SingletonTrait;
16
17
18
if (!defined('LOG_DIR')) {
19
    GeneratorHelper::createDir(BASE_DIR . DIRECTORY_SEPARATOR . 'logs');
20
    define('LOG_DIR', BASE_DIR . DIRECTORY_SEPARATOR . 'logs');
21
}
22
23
/**
24
 * Class Logger
25
 * @package PSFS\base
26
 * Servicio de log
27
 */
28
class Logger
29
{
30
    const DEFAULT_NAMESPACE = 'PSFS';
31
    use SingletonTrait;
32
    /**
33
     * @var \Monolog\Logger
34
     */
35
    protected $logger;
36
    /**
37
     * @var resource
38
     */
39
    private $stream;
40
    /**
41
     * @var UidProcessor
42
     */
43
    private $uuid;
44
    /**
45
     * @var string
46
     */
47
    protected $log_level;
48
49
    /**
50
     * Logger constructor.
51
     * @throws exception\GeneratorException
52
     */
53 1
    public function __construct()
54
    {
55 1
        $config = Config::getInstance();
56 1
        $args = func_get_args();
57 1
        list($logger, $debug, $path) = $this->setup($config, $args);
58 1
        $this->stream = fopen($path . DIRECTORY_SEPARATOR . date('Ymd') . '.log', 'a+');
59 1
        $this->addPushLogger($logger, $debug, $config);
60 1
        $this->log_level = Config::getParam('log.level', 'info');
61 1
    }
62
63
    public function __destruct()
64
    {
65
        fclose($this->stream);
66
    }
67
68
    /**
69
     * @param string $logger
70
     * @param boolean $debug
71
     * @param Config $config
72
     * @throws \Exception
73
     */
74 1
    private function addPushLogger($logger, $debug, Config $config)
75
    {
76 1
        $this->logger = new Monolog(strtoupper($logger));
77 1
        $this->logger->pushHandler($this->addDefaultStreamHandler($debug));
78 1
        if ($debug) {
79 1
            $phpFireLog = $config->get('logger.phpFire');
80 1
            if (!empty($phpFireLog)) {
81
                $this->logger->pushHandler(new FirePHPHandler());
82
            }
83 1
            $memoryLog = $config->get('logger.memory');
84 1
            if (!empty($memoryLog)) {
85
                $this->logger->pushProcessor(new MemoryUsageProcessor());
86
            }
87
        }
88 1
        $this->uuid = new UidProcessor();
89 1
        $this->logger->pushProcessor($this->uuid);
90 1
    }
91
92
    /**
93
     * @param Config $config
94
     * @param array $args
95
     * @return array
96
     * @throws exception\GeneratorException
97
     */
98 1
    private function setup(Config $config, array $args = [])
99
    {
100 1
        $args = $args ?? [];
101 1
        $debug = $config->getDebugMode();
102 1
        $namespace = self::DEFAULT_NAMESPACE;
103 1
        if (0 !== count($args)) {
104 1
            $namespace = $args[0][0] ?? 'PSFS';
105 1
            $debug = $args[0][1] ?? true;
106
        }
107 1
        $path = $this->createLoggerPath($config);
108 1
        return array($this->cleanLoggerName($namespace), $debug, $path);
109
    }
110
111
    /**
112
     * @param Config $config
113
     *
114
     * @return string
115
     */
116 1
    private function setLoggerName(Config $config)
117
    {
118 1
        $logger = $config->get('platform_name') ?: self::DEFAULT_NAMESPACE;
119 1
        $logger = $this->cleanLoggerName($logger);
120
121 1
        return $logger;
122
    }
123
124
    /**
125
     * @param $logger
126
     *
127
     * @return mixed
128
     */
129 1
    private function cleanLoggerName($logger)
130
    {
131 1
        $logger = str_replace(' ', '', $logger);
132 1
        $logger = preg_replace('/\\\/', ".", $logger);
133
134 1
        return $logger;
135
    }
136
137
    /**
138
     * @param Config $config
139
     * @return string
140
     * @throws exception\GeneratorException
141
     */
142 1
    private function createLoggerPath(Config $config)
143
    {
144 1
        $logger = $this->setLoggerName($config);
145 1
        $path = LOG_DIR . DIRECTORY_SEPARATOR . $logger . DIRECTORY_SEPARATOR . date('Y') . DIRECTORY_SEPARATOR . date('m');
146 1
        GeneratorHelper::createDir($path);
147
148 1
        return $path;
149
    }
150
151
    /**
152
     * @param string $msg
153
     * @param int $type
154
     * @param array $context
155
     * @return bool
156
     */
157 28
    public function addLog($msg, $type = LOG_DEBUG, array $context = []) {
158 28
        return $this->logger->addRecord($type, $msg, $this->addMinimalContext($context));
159
    }
160
161
    /**
162
     * @param string $msg
163
     * @param int $type
164
     * @param array $context
0 ignored issues
show
Documentation introduced by
Should the type for parameter $context not be null|array? Also, consider making the array more specific, something like array<String>, or String[].

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive. In addition it looks for parameters that have the generic type array and suggests a stricter type like array<String>.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
165
     */
166 28
    public static function log($msg, $type = LOG_DEBUG, array $context = null)
167
    {
168 28
        if(null === $context) {
169 18
            $context = [];
170
        }
171 28
        if(Config::getParam('profiling.enable')) {
172
            Inspector::stats($msg);
173
        }
174
        switch ($type) {
175 28
            case LOG_CRIT:
176
                if(Config::getParam('log.slack.hook')) {
177
                    SlackHelper::getInstance()->trace($msg, '', '', $context);
178
                }
179 28
            case LOG_ERR:
180
                self::getInstance()->addLog($msg, $type, $context);
181
                break;
182
            default:
183 28
                self::getInstance()->addLog($msg, $type, $context);
184
                break;
185
        }
186
    }
187
188
    /**
189
     * @param bool $debug
190
     * @return StreamHandler
191
     * @throws \Exception
192
     */
193 1
    private function addDefaultStreamHandler($debug = false)
194
    {
195
        // the default date format is "Y-m-d H:i:s"
196 1
        $dateFormat = 'Y-m-d H:i:s.u';
197
        // the default output format is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"
198 1
        $output = "[%datetime%] [%channel%:%level_name%]\t%message%\t%context%\t%extra%\n";
199
        // finally, create a formatter
200 1
        $formatter = new LineFormatter($output, $dateFormat);
201 1
        $stream = new StreamHandler($this->stream, $debug ? Monolog::DEBUG : Monolog::WARNING);
202 1
        $stream->setFormatter($formatter);
203 1
        return $stream;
204
    }
205
206
    /**
207
     * @param array $context
208
     * @return array
209
     */
210 28
    private function addMinimalContext(array $context = [])
211
    {
212 28
        $context['uri'] = null !== $_SERVER && array_key_exists('REQUEST_URI', $_SERVER) ? $_SERVER['REQUEST_URI'] : 'Unknow';
213 28
        $context['method'] = null !== $_SERVER && array_key_exists('REQUEST_METHOD', $_SERVER) ? $_SERVER['REQUEST_METHOD'] : 'Unknow';
214 28
        if(null !== $_SERVER && array_key_exists('HTTP_X_PSFS_UID', $_SERVER)) {
215
            $context['uid'] = $_SERVER['HTTP_X_PSFS_UID'];
216
        }
217 28
        return $context;
218
    }
219
220
    /**
221
     * @return string
222
     */
223
    public function getLogUid() {
224
        return $this->uuid->getUid();
225
    }
226
227
    /**
228
     * @return string
229
     */
230
    public static function getUid() {
231
        return self::getInstance()->getLogUid();
232
    }
233
}
234