Passed
Push — master ( 415c39...a18509 )
by Fran
11:01
created

Logger::defaultLog()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
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
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 19 and the first side effect is on line 18.

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\traits\SingletonTrait;
15
16
17
if (!defined('LOG_DIR')) {
18
    GeneratorHelper::createDir(BASE_DIR . DIRECTORY_SEPARATOR . 'logs');
19
    define('LOG_DIR', BASE_DIR . DIRECTORY_SEPARATOR . 'logs');
20
}
21
22
/**
23
 * Class Logger
24
 * @package PSFS\base
25
 * Servicio de log
26
 */
27
class Logger
28
{
29
    const DEFAULT_NAMESPACE = 'PSFS';
30
    use SingletonTrait;
31
    /**
32
     * @var \Monolog\Logger
33
     */
34
    protected $logger;
35
    /**
36
     * @var resource
37
     */
38
    private $stream;
39
    /**
40
     * @var UidProcessor
41
     */
42
    private $uuid;
43
    /**
44
     * @var string
45
     */
46
    protected $log_level;
47
48
    /**
49
     * Logger constructor.
50
     * @throws exception\GeneratorException
51
     */
52 2
    public function __construct()
53
    {
54 2
        $config = Config::getInstance();
55 2
        $args = func_get_args();
56 2
        list($logger, $debug, $path) = $this->setup($config, $args);
57 2
        $this->stream = fopen($path . DIRECTORY_SEPARATOR . date('Ymd') . '.log', 'a+');
58 2
        $this->addPushLogger($logger, $debug, $config);
59 2
        $this->log_level = Config::getParam('log.level', 'info');
60 2
    }
61
62 1
    public function __destruct()
63
    {
64 1
        fclose($this->stream);
65 1
    }
66
67
    /**
68
     * @param string $msg
69
     * @param array $context
70
     * @return bool
71
     */
72 1
    public function defaultLog($msg = '', array $context = [])
73
    {
74 1
        return $this->logger->addNotice($msg, $this->addMinimalContext($context));
75
    }
76
77
    /**
78
     * @param string $msg
79
     * @param array $context
80
     *
81
     * @return bool
82
     */
83 4
    public function infoLog($msg = '', array $context = [])
84
    {
85 4
        return $this->logger->addInfo($msg, $this->addMinimalContext($context));
86
    }
87
88
    /**
89
     * @param string $msg
90
     * @param array $context
91
     *
92
     * @return bool
93
     */
94 21
    public function debugLog($msg = '', array $context = [])
95
    {
96 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...
97
    }
98
99
    /**
100
     * @param $msg
101
     * @param array $context
102
     *
103
     * @return bool
104
     */
105 4
    public function errorLog($msg, array $context = [])
106
    {
107 4
        return $this->logger->addError($msg, $this->addMinimalContext($context));
108
    }
109
110
    /**
111
     * @param $msg
112
     * @param array $context
113
     * @return bool
114
     */
115 2
    public function warningLog($msg, array $context = [])
116
    {
117 2
        return $this->logger->addWarning($msg, $this->addMinimalContext($context));
118
    }
119
120
    /**
121
     * @param string $logger
122
     * @param boolean $debug
123
     * @param Config $config
124
     * @throws \Exception
125
     */
126 2
    private function addPushLogger($logger, $debug, Config $config)
127
    {
128 2
        $this->logger = new Monolog(strtoupper($logger));
129 2
        $this->logger->pushHandler($this->addDefaultStreamHandler($debug));
130 2
        if ($debug) {
131 1
            $phpFireLog = $config->get('logger.phpFire');
132 1
            if (!empty($phpFireLog)) {
133 1
                $this->logger->pushHandler(new FirePHPHandler());
134
            }
135 1
            $memoryLog = $config->get('logger.memory');
136 1
            if (!empty($memoryLog)) {
137 1
                $this->logger->pushProcessor(new MemoryUsageProcessor());
138
            }
139
        }
140 2
        $this->uuid = new UidProcessor();
141 2
        $this->logger->pushProcessor($this->uuid);
142 2
    }
143
144
    /**
145
     * @param Config $config
146
     * @param array $args
147
     * @return array
148
     * @throws exception\GeneratorException
149
     */
150 2
    private function setup(Config $config, array $args = array())
151
    {
152 2
        $debug = $config->getDebugMode();
153 2
        $namespace = self::DEFAULT_NAMESPACE;
154 2
        if (0 !== count($args)) {
155 2
            if (array_key_exists(0, $args) && array_key_exists(0, $args[0])) {
156 1
                $namespace = $args[0][0];
157
            }
158 2
            if (array_key_exists(0, $args) && array_key_exists(1, $args[0])) {
159 1
                $debug = $args[0][1];
160
            }
161
        }
162 2
        $path = $this->createLoggerPath($config);
163 2
        return array($this->cleanLoggerName($namespace), $debug, $path);
164
    }
165
166
    /**
167
     * @param Config $config
168
     *
169
     * @return string
170
     */
171 2
    private function setLoggerName(Config $config)
172
    {
173 2
        $logger = $config->get('platform_name') ?: self::DEFAULT_NAMESPACE;
174 2
        $logger = $this->cleanLoggerName($logger);
175
176 2
        return $logger;
177
    }
178
179
    /**
180
     * @param $logger
181
     *
182
     * @return mixed
183
     */
184 2
    private function cleanLoggerName($logger)
185
    {
186 2
        $logger = str_replace(' ', '', $logger);
187 2
        $logger = preg_replace('/\\\/', ".", $logger);
188
189 2
        return $logger;
190
    }
191
192
    /**
193
     * @param Config $config
194
     * @return string
195
     * @throws exception\GeneratorException
196
     */
197 2
    private function createLoggerPath(Config $config)
198
    {
199 2
        $logger = $this->setLoggerName($config);
200 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...
201 2
        GeneratorHelper::createDir($path);
202
203 2
        return $path;
204
    }
205
206
    /**
207
     * @param string $msg
208
     * @param int $type
209
     * @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...
210
     */
211 22
    public static function log($msg, $type = LOG_DEBUG, array $context = null)
212
    {
213 22
        if(null === $context) {
214 22
            $context = [];
215
        }
216 22
        if(Config::getParam('profiling.enable')) {
217 1
            Inspector::stats($msg);
218
        }
219
        switch ($type) {
220 22
            case LOG_DEBUG:
221 21
                self::getInstance()->debugLog($msg, $context);
222 21
                break;
223 7
            case LOG_WARNING:
224 2
                self::getInstance()->warningLog($msg, $context);
225 2
                break;
226 7
            case LOG_CRIT:
227 7
            case LOG_ERR:
228 4
                self::getInstance()->errorLog($msg, $context);
229 4
                break;
230 4
            case LOG_INFO:
231 4
                self::getInstance()->infoLog($msg, $context);
232 4
                break;
233
            default:
234 1
                self::getInstance()->defaultLog($msg, $context);
235 1
                break;
236
        }
237 22
    }
238
239
    /**
240
     * @param bool $debug
241
     * @return StreamHandler
242
     * @throws \Exception
243
     */
244 2
    private function addDefaultStreamHandler($debug = false)
245
    {
246
        // the default date format is "Y-m-d H:i:s"
247 2
        $dateFormat = 'Y-m-d H:i:s.u';
248
        // the default output format is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"
249 2
        $output = "[%datetime%] [%channel%:%level_name%]\t%message%\t%context%\t%extra%\n";
250
        // finally, create a formatter
251 2
        $formatter = new LineFormatter($output, $dateFormat);
252 2
        $stream = new StreamHandler($this->stream, $debug ? Monolog::DEBUG : Monolog::WARNING);
253 2
        $stream->setFormatter($formatter);
254 2
        return $stream;
255
    }
256
257
    /**
258
     * @param array $context
259
     * @return array
260
     */
261 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...
262
    {
263 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...
264 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...
265 7
        if(null !== $_SERVER && array_key_exists('HTTP_X_PSFS_UID', $_SERVER)) {
266
            $context['uid'] = $_SERVER['HTTP_X_PSFS_UID'];
267
        }
268 7
        return $context;
269
    }
270
271
    /**
272
     * @return string
273
     */
274
    public function getLogUid() {
275
        return $this->uuid->getUid();
276
    }
277
278
    /**
279
     * @return string
280
     */
281
    public static function getUid() {
282
        return self::getInstance()->getLogUid();
283
    }
284
}
285