Target::setLevels()   A
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 26
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 19
nc 5
nop 1
dl 0
loc 26
ccs 20
cts 20
cp 1
crap 6
rs 9.0111
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\log;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\base\InvalidConfigException;
13
use yii\helpers\ArrayHelper;
14
use yii\helpers\StringHelper;
15
use yii\helpers\VarDumper;
16
use yii\web\Request;
17
18
/**
19
 * Target is the base class for all log target classes.
20
 *
21
 * A log target object will filter the messages logged by [[Logger]] according
22
 * to its [[levels]] and [[categories]] properties. It may also export the filtered
23
 * messages to specific destination defined by the target, such as emails, files.
24
 *
25
 * Level filter and category filter are combinatorial, i.e., only messages
26
 * satisfying both filter conditions will be handled. Additionally, you
27
 * may specify [[except]] to exclude messages of certain categories.
28
 *
29
 * @property bool $enabled Indicates whether this log target is enabled. Defaults to true. Note that the type
30
 * of this property differs in getter and setter. See [[getEnabled()]] and [[setEnabled()]] for details.
31
 * @property int $levels The message levels that this target is interested in. This is a bitmap of level
32
 * values. Defaults to 0, meaning all available levels. Note that the type of this property differs in getter and
33
 * setter. See [[getLevels()]] and [[setLevels()]] for details.
34
 *
35
 * For more details and usage information on Target, see the [guide article on logging & targets](guide:runtime-logging).
36
 *
37
 * @author Qiang Xue <[email protected]>
38
 * @since 2.0
39
 */
40
abstract class Target extends Component
41
{
42
    /**
43
     * @var array list of message categories that this target is interested in. Defaults to empty, meaning all categories.
44
     * You can use an asterisk at the end of a category so that the category may be used to
45
     * match those categories sharing the same common prefix. For example, 'yii\db\*' will match
46
     * categories starting with 'yii\db\', such as 'yii\db\Connection'.
47
     */
48
    public $categories = [];
49
    /**
50
     * @var array list of message categories that this target is NOT interested in. Defaults to empty, meaning no uninteresting messages.
51
     * If this property is not empty, then any category listed here will be excluded from [[categories]].
52
     * You can use an asterisk at the end of a category so that the category can be used to
53
     * match those categories sharing the same common prefix. For example, 'yii\db\*' will match
54
     * categories starting with 'yii\db\', such as 'yii\db\Connection'.
55
     * @see categories
56
     */
57
    public $except = [];
58
    /**
59
     * @var array list of the PHP predefined variables that should be logged in a message.
60
     * Note that a variable must be accessible via `$GLOBALS`. Otherwise it won't be logged.
61
     *
62
     * Defaults to `['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER']`.
63
     *
64
     * Since version 2.0.9 additional syntax can be used:
65
     * Each element could be specified as one of the following:
66
     *
67
     * - `var` - `var` will be logged.
68
     * - `var.key` - only `var[key]` key will be logged.
69
     * - `!var.key` - `var[key]` key will be excluded.
70
     *
71
     * Note that if you need $_SESSION to logged regardless if session was used you have to open it right at
72
     * the start of your request.
73
     *
74
     * @see \yii\helpers\ArrayHelper::filter()
75
     */
76
    public $logVars = [
77
        '_GET',
78
        '_POST',
79
        '_FILES',
80
        '_COOKIE',
81
        '_SESSION',
82
        '_SERVER',
83
    ];
84
    /**
85
     * @var array list of the PHP predefined variables that should NOT be logged "as is" and should always be replaced
86
     * with a mask `***` before logging, when exist.
87
     *
88
     * Defaults to `[ '_SERVER.HTTP_AUTHORIZATION', '_SERVER.PHP_AUTH_USER', '_SERVER.PHP_AUTH_PW']`
89
     *
90
     * Each element could be specified as one of the following:
91
     *
92
     * - `var` - `var` will be logged as `***`
93
     * - `var.key` - only `var[key]` will be logged as `***`
94
     *
95
     * In addition, this property accepts (case-insensitive) patterns. For example:
96
     * - `_SERVER.*_SECRET` matches all ending with `_SECRET`, such as `$_SERVER['TOKEN_SECRET']` etc.
97
     * - `_SERVER.SECRET_*` matches all starting with `SECRET_`, such as `$_SERVER['SECRET_TOKEN']` etc.
98
     * - `_SERVER.*SECRET*` matches all containing `SECRET` i.e. both of the above.
99
     *
100
     * @since 2.0.16
101
     */
102
    public $maskVars = [
103
        '_SERVER.HTTP_AUTHORIZATION',
104
        '_SERVER.PHP_AUTH_USER',
105
        '_SERVER.PHP_AUTH_PW',
106
    ];
107
    /**
108
     * @var callable|null a PHP callable that returns a string to be prefixed to every exported message.
109
     *
110
     * If not set, [[getMessagePrefix()]] will be used, which prefixes the message with context information
111
     * such as user IP, user ID and session ID.
112
     *
113
     * The signature of the callable should be `function ($message)`.
114
     */
115
    public $prefix;
116
    /**
117
     * @var int how many messages should be accumulated before they are exported.
118
     * Defaults to 1000. Note that messages will always be exported when the application terminates.
119
     * Set this property to be 0 if you don't want to export messages until the application terminates.
120
     */
121
    public $exportInterval = 1000;
122
    /**
123
     * @var array the messages that are retrieved from the logger so far by this log target.
124
     * Please refer to [[Logger::messages]] for the details about the message structure.
125
     */
126
    public $messages = [];
127
    /**
128
     * @var bool whether to log time with microseconds.
129
     * Defaults to false.
130
     * @since 2.0.13
131
     */
132
    public $microtime = false;
133
134
    private $_levels = 0;
135
    private $_enabled = true;
136
137
138
    /**
139
     * Exports log [[messages]] to a specific destination.
140
     * Child classes must implement this method.
141
     */
142
    abstract public function export();
143
144
    /**
145
     * Processes the given log messages.
146
     * This method will filter the given messages with [[levels]] and [[categories]].
147
     * And if requested, it will also export the filtering result to specific medium (e.g. email).
148
     * @param array $messages log messages to be processed. See [[Logger::messages]] for the structure
149
     * of each message.
150
     * @param bool $final whether this method is called at the end of the current application
151
     */
152 22
    public function collect($messages, $final)
153
    {
154 22
        $this->messages = array_merge($this->messages, static::filterMessages($messages, $this->getLevels(), $this->categories, $this->except));
155 22
        $count = count($this->messages);
156 22
        if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) {
157 21
            if (($context = $this->getContextMessage()) !== '') {
158 1
                $this->messages[] = [$context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME, [], 0];
159
            }
160
            // set exportInterval to 0 to avoid triggering export again while exporting
161 21
            $oldExportInterval = $this->exportInterval;
162 21
            $this->exportInterval = 0;
163 21
            $this->export();
164 21
            $this->exportInterval = $oldExportInterval;
165
166 21
            $this->messages = [];
167
        }
168
    }
169
170
    /**
171
     * Generates the context information to be logged.
172
     * The default implementation will dump user information, system variables, etc.
173
     * @return string the context information. If an empty string, it means no context information.
174
     */
175 23
    protected function getContextMessage()
176
    {
177 23
        $context = ArrayHelper::filter($GLOBALS, $this->logVars);
178 23
        $items = ArrayHelper::flatten($context);
179 23
        foreach ($this->maskVars as $var) {
180 23
            foreach ($items as $key => $value) {
181 3
                if (StringHelper::matchWildcard($var, $key, ['caseSensitive' => false])) {
182 2
                    ArrayHelper::setValue($context, $key, '***');
183
                }
184
            }
185
        }
186 23
        $result = [];
187 23
        foreach ($context as $key => $value) {
188 3
            $result[] = "\${$key} = " . VarDumper::dumpAsString($value);
189
        }
190
191 23
        return implode("\n\n", $result);
192
    }
193
194
    /**
195
     * @return int the message levels that this target is interested in. This is a bitmap of
196
     * level values. Defaults to 0, meaning all available levels.
197
     */
198 24
    public function getLevels()
199
    {
200 24
        return $this->_levels;
201
    }
202
203
    /**
204
     * Sets the message levels that this target is interested in.
205
     *
206
     * The parameter can be either an array of interested level names or an integer representing
207
     * the bitmap of the interested level values. Valid level names include: 'error',
208
     * 'warning', 'info', 'trace' and 'profile'; valid level values include:
209
     * [[Logger::LEVEL_ERROR]], [[Logger::LEVEL_WARNING]], [[Logger::LEVEL_INFO]],
210
     * [[Logger::LEVEL_TRACE]] and [[Logger::LEVEL_PROFILE]].
211
     *
212
     * For example,
213
     *
214
     * ```php
215
     * ['error', 'warning']
216
     * // which is equivalent to:
217
     * Logger::LEVEL_ERROR | Logger::LEVEL_WARNING
218
     * ```
219
     *
220
     * @param array|int $levels message levels that this target is interested in.
221
     * @throws InvalidConfigException if $levels value is not correct.
222
     */
223 12
    public function setLevels($levels)
224
    {
225 12
        static $levelMap = [
226 12
            'error' => Logger::LEVEL_ERROR,
227 12
            'warning' => Logger::LEVEL_WARNING,
228 12
            'info' => Logger::LEVEL_INFO,
229 12
            'trace' => Logger::LEVEL_TRACE,
230 12
            'profile' => Logger::LEVEL_PROFILE,
231 12
        ];
232 12
        if (is_array($levels)) {
233 4
            $this->_levels = 0;
234 4
            foreach ($levels as $level) {
235 4
                if (isset($levelMap[$level])) {
236 4
                    $this->_levels |= $levelMap[$level];
237
                } else {
238 1
                    throw new InvalidConfigException("Unrecognized level: $level");
239
                }
240
            }
241
        } else {
242 8
            $bitmapValues = array_reduce($levelMap, function ($carry, $item) {
243 8
                return $carry | $item;
244 8
            });
245 8
            if (!($bitmapValues & $levels) && $levels !== 0) {
246 1
                throw new InvalidConfigException("Incorrect $levels value");
247
            }
248 8
            $this->_levels = $levels;
249
        }
250
    }
251
252
    /**
253
     * Filters the given messages according to their categories and levels.
254
     * @param array $messages messages to be filtered.
255
     * The message structure follows that in [[Logger::messages]].
256
     * @param int $levels the message levels to filter by. This is a bitmap of
257
     * level values. Value 0 means allowing all levels.
258
     * @param array $categories the message categories to filter by. If empty, it means all categories are allowed.
259
     * @param array $except the message categories to exclude. If empty, it means all categories are allowed.
260
     * @return array the filtered messages.
261
     */
262 22
    public static function filterMessages($messages, $levels = 0, $categories = [], $except = [])
263
    {
264 22
        foreach ($messages as $i => $message) {
265 22
            if ($levels && !($levels & $message[1])) {
266 7
                unset($messages[$i]);
267 7
                continue;
268
            }
269
270 22
            $matched = empty($categories);
271 22
            foreach ($categories as $category) {
272 12
                if ($message[2] === $category || !empty($category) && substr_compare($category, '*', -1, 1) === 0 && strpos($message[2], rtrim($category, '*')) === 0) {
273 11
                    $matched = true;
274 11
                    break;
275
                }
276
            }
277
278 22
            if ($matched) {
279 21
                foreach ($except as $category) {
280 3
                    $prefix = rtrim($category, '*');
281 3
                    if (($message[2] === $category || $prefix !== $category) && strpos($message[2], $prefix) === 0) {
282 3
                        $matched = false;
283 3
                        break;
284
                    }
285
                }
286
            }
287
288 22
            if (!$matched) {
289 13
                unset($messages[$i]);
290
            }
291
        }
292
293 22
        return $messages;
294
    }
295
296
    /**
297
     * Formats a log message for display as a string.
298
     * @param array $message the log message to be formatted.
299
     * The message structure follows that in [[Logger::messages]].
300
     * @return string the formatted message
301
     */
302 2
    public function formatMessage($message)
303
    {
304 2
        [$text, $level, $category, $timestamp] = $message;
305 2
        $level = Logger::getLevelName($level);
306 2
        if (!is_string($text)) {
307
            // exceptions may not be serializable if in the call stack somewhere is a Closure
308
            if ($text instanceof \Exception || $text instanceof \Throwable) {
309
                $text = (string) $text;
310
            } else {
311
                $text = VarDumper::export($text);
312
            }
313
        }
314 2
        $traces = [];
315 2
        if (isset($message[4])) {
316 1
            foreach ($message[4] as $trace) {
317
                $traces[] = "in {$trace['file']}:{$trace['line']}";
318
            }
319
        }
320
321 2
        $prefix = $this->getMessagePrefix($message);
322 2
        return $this->getTime($timestamp) . " {$prefix}[$level][$category] $text"
323 2
            . (empty($traces) ? '' : "\n    " . implode("\n    ", $traces));
324
    }
325
326
    /**
327
     * Returns a string to be prefixed to the given message.
328
     * If [[prefix]] is configured it will return the result of the callback.
329
     * The default implementation will return user IP, user ID and session ID as a prefix.
330
     * @param array $message the message being exported.
331
     * The message structure follows that in [[Logger::messages]].
332
     * @return string the prefix string
333
     */
334 2
    public function getMessagePrefix($message)
335
    {
336 2
        if ($this->prefix !== null) {
337
            return call_user_func($this->prefix, $message);
338
        }
339
340 2
        if (Yii::$app === null) {
341 1
            return '';
342
        }
343
344 1
        $request = Yii::$app->getRequest();
345 1
        $ip = $request instanceof Request ? $request->getUserIP() : '-';
346
347
        /** @var \yii\web\User $user */
348 1
        $user = Yii::$app->has('user', true) ? Yii::$app->get('user') : null;
349 1
        if ($user && ($identity = $user->getIdentity(false))) {
350
            $userID = $identity->getId();
351
        } else {
352 1
            $userID = '-';
353
        }
354
355
        /** @var \yii\web\Session $session */
356 1
        $session = Yii::$app->has('session', true) ? Yii::$app->get('session') : null;
357 1
        $sessionID = $session && $session->getIsActive() ? $session->getId() : '-';
358
359 1
        return "[$ip][$userID][$sessionID]";
360
    }
361
362
    /**
363
     * Sets a value indicating whether this log target is enabled.
364
     * @param bool|callable $value a boolean value or a callable to obtain the value from.
365
     * The callable value is available since version 2.0.13.
366
     *
367
     * A callable may be used to determine whether the log target should be enabled in a dynamic way.
368
     * For example, to only enable a log if the current user is logged in you can configure the target
369
     * as follows:
370
     *
371
     * ```php
372
     * 'enabled' => function() {
373
     *     return !Yii::$app->user->isGuest;
374
     * }
375
     * ```
376
     */
377 2
    public function setEnabled($value)
378
    {
379 2
        $this->_enabled = $value;
380
    }
381
382
    /**
383
     * Check whether the log target is enabled.
384
     * @property bool Indicates whether this log target is enabled. Defaults to true.
385
     * @return bool A value indicating whether this log target is enabled.
386
     */
387 23
    public function getEnabled()
388
    {
389 23
        if (is_callable($this->_enabled)) {
390 1
            return call_user_func($this->_enabled, $this);
0 ignored issues
show
Bug introduced by
$this->_enabled of type boolean is incompatible with the type callable expected by parameter $callback of call_user_func(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

390
            return call_user_func(/** @scrutinizer ignore-type */ $this->_enabled, $this);
Loading history...
391
        }
392
393 23
        return $this->_enabled;
394
    }
395
396
    /**
397
     * Returns formatted ('Y-m-d H:i:s') timestamp for message.
398
     * If [[microtime]] is configured to true it will return format 'Y-m-d H:i:s.u'.
399
     * @param float $timestamp
400
     * @return string
401
     * @since 2.0.13
402
     */
403 2
    protected function getTime($timestamp)
404
    {
405 2
        $parts = explode('.', sprintf('%F', $timestamp));
406
407 2
        return date('Y-m-d H:i:s', $parts[0]) . ($this->microtime ? ('.' . $parts[1]) : '');
0 ignored issues
show
Bug introduced by
$parts[0] of type string is incompatible with the type integer|null expected by parameter $timestamp of date(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

407
        return date('Y-m-d H:i:s', /** @scrutinizer ignore-type */ $parts[0]) . ($this->microtime ? ('.' . $parts[1]) : '');
Loading history...
408
    }
409
}
410