Passed
Push — master ( 08392e...cc821f )
by Fran
09:32
created

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