Passed
Push — master ( e25047...d6dcc5 )
by Fran
04:44
created

Logger::criticalLog()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 2
dl 0
loc 7
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 10
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 20 and the first side effect is on line 19.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
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 2
    public function __construct()
54
    {
55 2
        $config = Config::getInstance();
56 2
        $args = func_get_args();
57 2
        list($logger, $debug, $path) = $this->setup($config, $args);
58 2
        $this->stream = fopen($path . DIRECTORY_SEPARATOR . date('Ymd') . '.log', 'a+');
59 2
        $this->addPushLogger($logger, $debug, $config);
60 2
        $this->log_level = Config::getParam('log.level', 'info');
61 2
    }
62
63 1
    public function __destruct()
64
    {
65 1
        fclose($this->stream);
66 1
    }
67
68
    /**
69
     * @param string $msg
70
     * @param array $context
71
     * @return bool
72
     */
73 1
    public function defaultLog($msg = '', array $context = [])
74
    {
75 1
        return $this->logger->addNotice($msg, $this->addMinimalContext($context));
76
    }
77
78
    /**
79
     * @param string $msg
80
     * @param array $context
81
     *
82
     * @return bool
83
     */
84 4
    public function infoLog($msg = '', array $context = [])
85
    {
86 4
        return $this->logger->addInfo($msg, $this->addMinimalContext($context));
87
    }
88
89
    /**
90
     * @param string $msg
91
     * @param array $context
92
     *
93
     * @return bool
94
     */
95 21
    public function debugLog($msg = '', array $context = [])
96
    {
97 21
        return ($this->log_level === 'debug') ? $this->logger->addDebug($msg, $this->addMinimalContext($context)) : null;
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
98
    }
99
100
    /**
101
     * @param $msg
102
     * @param array $context
103
     *
104
     * @return bool
105
     */
106 4
    public function errorLog($msg, array $context = [])
107
    {
108 4
        return $this->logger->addError($msg, $this->addMinimalContext($context));
109
    }
110
111
    /**
112
     * @param $msg
113
     * @param array $context
114
     *
115
     * @return bool
116
     */
117 1
    public function criticalLog($msg, array $context = [])
118
    {
119 1
        if(Config::getParam('log.slack.hook')) {
120
            SlackHelper::getInstance()->trace($msg, '', '', $context);
121
        }
122 1
        return $this->logger->addCritical($msg, $this->addMinimalContext($context));
123
    }
124
125
    /**
126
     * @param $msg
127
     * @param array $context
128
     * @return bool
129
     */
130 2
    public function warningLog($msg, array $context = [])
131
    {
132 2
        return $this->logger->addWarning($msg, $this->addMinimalContext($context));
133
    }
134
135
    /**
136
     * @param string $logger
137
     * @param boolean $debug
138
     * @param Config $config
139
     * @throws \Exception
140
     */
141 2
    private function addPushLogger($logger, $debug, Config $config)
142
    {
143 2
        $this->logger = new Monolog(strtoupper($logger));
144 2
        $this->logger->pushHandler($this->addDefaultStreamHandler($debug));
145 2
        if ($debug) {
146 1
            $phpFireLog = $config->get('logger.phpFire');
147 1
            if (!empty($phpFireLog)) {
148 1
                $this->logger->pushHandler(new FirePHPHandler());
149
            }
150 1
            $memoryLog = $config->get('logger.memory');
151 1
            if (!empty($memoryLog)) {
152 1
                $this->logger->pushProcessor(new MemoryUsageProcessor());
153
            }
154
        }
155 2
        $this->uuid = new UidProcessor();
156 2
        $this->logger->pushProcessor($this->uuid);
157 2
    }
158
159
    /**
160
     * @param Config $config
161
     * @param array $args
162
     * @return array
163
     * @throws exception\GeneratorException
164
     */
165 2
    private function setup(Config $config, array $args = array())
166
    {
167 2
        $debug = $config->getDebugMode();
168 2
        $namespace = self::DEFAULT_NAMESPACE;
169 2
        if (0 !== count($args)) {
170 2
            if (array_key_exists(0, $args) && array_key_exists(0, $args[0])) {
171 1
                $namespace = $args[0][0];
172
            }
173 2
            if (array_key_exists(0, $args) && array_key_exists(1, $args[0])) {
174 1
                $debug = $args[0][1];
175
            }
176
        }
177 2
        $path = $this->createLoggerPath($config);
178 2
        return array($this->cleanLoggerName($namespace), $debug, $path);
179
    }
180
181
    /**
182
     * @param Config $config
183
     *
184
     * @return string
185
     */
186 2
    private function setLoggerName(Config $config)
187
    {
188 2
        $logger = $config->get('platform_name') ?: self::DEFAULT_NAMESPACE;
189 2
        $logger = $this->cleanLoggerName($logger);
190
191 2
        return $logger;
192
    }
193
194
    /**
195
     * @param $logger
196
     *
197
     * @return mixed
198
     */
199 2
    private function cleanLoggerName($logger)
200
    {
201 2
        $logger = str_replace(' ', '', $logger);
202 2
        $logger = preg_replace('/\\\/', ".", $logger);
203
204 2
        return $logger;
205
    }
206
207
    /**
208
     * @param Config $config
209
     * @return string
210
     * @throws exception\GeneratorException
211
     */
212 2
    private function createLoggerPath(Config $config)
213
    {
214 2
        $logger = $this->setLoggerName($config);
215 2
        $path = LOG_DIR . DIRECTORY_SEPARATOR . $logger . DIRECTORY_SEPARATOR . date('Y') . DIRECTORY_SEPARATOR . date('m');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 124 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
216 2
        GeneratorHelper::createDir($path);
217
218 2
        return $path;
219
    }
220
221
    /**
222
     * @param string $msg
223
     * @param int $type
224
     * @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...
225
     */
226 22
    public static function log($msg, $type = LOG_DEBUG, array $context = null)
227
    {
228 22
        if(null === $context) {
229 22
            $context = [];
230
        }
231 22
        if(Config::getParam('profiling.enable')) {
232 1
            Inspector::stats($msg);
233
        }
234
        switch ($type) {
235 22
            case LOG_DEBUG:
236 21
                self::getInstance()->debugLog($msg, $context);
237 21
                break;
238 7
            case LOG_WARNING:
239 2
                self::getInstance()->warningLog($msg, $context);
240 2
                break;
241 7
            case LOG_CRIT:
242 1
                self::getInstance()->criticalLog($msg, $context);
243 1
                break;
244 7
            case LOG_ERR:
245 4
                self::getInstance()->errorLog($msg, $context);
246 4
                break;
247 4
            case LOG_INFO:
248 4
                self::getInstance()->infoLog($msg, $context);
249 4
                break;
250
            default:
251 1
                self::getInstance()->defaultLog($msg, $context);
252 1
                break;
253
        }
254 22
    }
255
256
    /**
257
     * @param bool $debug
258
     * @return StreamHandler
259
     * @throws \Exception
260
     */
261 2
    private function addDefaultStreamHandler($debug = false)
262
    {
263
        // the default date format is "Y-m-d H:i:s"
264 2
        $dateFormat = 'Y-m-d H:i:s.u';
265
        // the default output format is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"
266 2
        $output = "[%datetime%] [%channel%:%level_name%]\t%message%\t%context%\t%extra%\n";
267
        // finally, create a formatter
268 2
        $formatter = new LineFormatter($output, $dateFormat);
269 2
        $stream = new StreamHandler($this->stream, $debug ? Monolog::DEBUG : Monolog::WARNING);
270 2
        $stream->setFormatter($formatter);
271 2
        return $stream;
272
    }
273
274
    /**
275
     * @param array $context
276
     * @return array
277
     */
278 7
    private function addMinimalContext(array $context = [])
0 ignored issues
show
Coding Style introduced by
addMinimalContext uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
279
    {
280 7
        $context['uri'] = null !== $_SERVER && array_key_exists('REQUEST_URI', $_SERVER) ? $_SERVER['REQUEST_URI'] : 'Unknow';
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
281 7
        $context['method'] = null !== $_SERVER && array_key_exists('REQUEST_METHOD', $_SERVER) ? $_SERVER['REQUEST_METHOD'] : 'Unknow';
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 135 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
282 7
        if(null !== $_SERVER && array_key_exists('HTTP_X_PSFS_UID', $_SERVER)) {
283
            $context['uid'] = $_SERVER['HTTP_X_PSFS_UID'];
284
        }
285 7
        return $context;
286
    }
287
288
    /**
289
     * @return string
290
     */
291
    public function getLogUid() {
292
        return $this->uuid->getUid();
293
    }
294
295
    /**
296
     * @return string
297
     */
298
    public static function getUid() {
299
        return self::getInstance()->getLogUid();
300
    }
301
}
302