Issues (902)

framework/log/Logger.php (1 issue)

Severity
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\base\Component;
11
12
/**
13
 * Logger records logged messages in memory and sends them to different targets if [[dispatcher]] is set.
14
 *
15
 * A Logger instance can be accessed via `Yii::getLogger()`. You can call the method [[log()]] to record a single log message.
16
 * For convenience, a set of shortcut methods are provided for logging messages of various severity levels
17
 * via the [[Yii]] class:
18
 *
19
 * - [[Yii::trace()]]
20
 * - [[Yii::error()]]
21
 * - [[Yii::warning()]]
22
 * - [[Yii::info()]]
23
 * - [[Yii::beginProfile()]]
24
 * - [[Yii::endProfile()]]
25
 *
26
 * For more details and usage information on Logger, see the [guide article on logging](guide:runtime-logging).
27
 *
28
 * When the application ends or [[flushInterval]] is reached, Logger will call [[flush()]]
29
 * to send logged messages to different log targets, such as [[FileTarget|file]], [[EmailTarget|email]],
30
 * or [[DbTarget|database]], with the help of the [[dispatcher]].
31
 *
32
 * @property-read array $dbProfiling The first element indicates the number of SQL statements executed, and
33
 * the second element the total time spent in SQL execution.
34
 * @property-read float $elapsedTime The total elapsed time in seconds for current request.
35
 * @property-read array $profiling The profiling results. Each element is an array consisting of these
36
 * elements: `info`, `category`, `timestamp`, `trace`, `level`, `duration`, `memory`, `memoryDiff`. The `memory`
37
 * and `memoryDiff` values are available since version 2.0.11.
38
 *
39
 * @author Qiang Xue <[email protected]>
40
 * @since 2.0
41
 */
42
class Logger extends Component
43
{
44
    /**
45
     * Error message level. An error message is one that indicates the abnormal termination of the
46
     * application and may require developer's handling.
47
     */
48
    const LEVEL_ERROR = 0x01;
49
    /**
50
     * Warning message level. A warning message is one that indicates some abnormal happens but
51
     * the application is able to continue to run. Developers should pay attention to this message.
52
     */
53
    const LEVEL_WARNING = 0x02;
54
    /**
55
     * Informational message level. An informational message is one that includes certain information
56
     * for developers to review.
57
     */
58
    const LEVEL_INFO = 0x04;
59
    /**
60
     * Tracing message level. A tracing message is one that reveals the code execution flow.
61
     */
62
    const LEVEL_TRACE = 0x08;
63
    /**
64
     * Profiling message level. This indicates the message is for profiling purpose.
65
     */
66
    const LEVEL_PROFILE = 0x40;
67
    /**
68
     * Profiling message level. This indicates the message is for profiling purpose. It marks the beginning
69
     * of a profiling block.
70
     */
71
    const LEVEL_PROFILE_BEGIN = 0x50;
72
    /**
73
     * Profiling message level. This indicates the message is for profiling purpose. It marks the end
74
     * of a profiling block.
75
     */
76
    const LEVEL_PROFILE_END = 0x60;
77
78
    /**
79
     * @var array logged messages. This property is managed by [[log()]] and [[flush()]].
80
     * Each log message is of the following structure:
81
     *
82
     * ```
83
     * [
84
     *   [0] => message (mixed, can be a string or some complex data, such as an exception object)
85
     *   [1] => level (integer)
86
     *   [2] => category (string)
87
     *   [3] => timestamp (float, obtained by microtime(true))
88
     *   [4] => traces (array, debug backtrace, contains the application code call stacks)
89
     *   [5] => memory usage in bytes (int, obtained by memory_get_usage()), available since version 2.0.11.
90
     * ]
91
     * ```
92
     */
93
    public $messages = [];
94
    /**
95
     * @var int how many messages should be logged before they are flushed from memory and sent to targets.
96
     * Defaults to 1000, meaning the [[flush()]] method will be invoked once every 1000 messages logged.
97
     * Set this property to be 0 if you don't want to flush messages until the application terminates.
98
     * This property mainly affects how much memory will be taken by the logged messages.
99
     * A smaller value means less memory, but will increase the execution time due to the overhead of [[flush()]].
100
     */
101
    public $flushInterval = 1000;
102
    /**
103
     * @var int how much call stack information (file name and line number) should be logged for each message.
104
     * If it is greater than 0, at most that number of call stacks will be logged. Note that only application
105
     * call stacks are counted.
106
     */
107
    public $traceLevel = 0;
108
    /**
109
     * @var Dispatcher the message dispatcher.
110
     */
111
    public $dispatcher;
112
    /**
113
     * @var array of event names used to get statistical results of DB queries.
114
     * @since 2.0.41
115
     */
116
    public $dbEventNames = ['yii\db\Command::query', 'yii\db\Command::execute'];
117
    /**
118
     * @var bool whether the profiling-aware mode should be switched on.
119
     * If on, [[flush()]] makes sure that profiling blocks are flushed in pairs. In case that any dangling messages are
120
     * detected these are kept for the next flush interval to find their pair. To prevent memory leaks, when number of
121
     * dangling messages reaches flushInterval value, logger flushes them immediately and triggers a warning.
122
     * Keep in mind that profiling-aware mode is more time and memory consuming.
123
     * @since 2.0.43
124
     */
125
    public $profilingAware = false;
126
127
128
    /**
129
     * Initializes the logger by registering [[flush()]] as a shutdown function.
130
     */
131 44
    public function init()
132
    {
133 44
        parent::init();
134 44
        register_shutdown_function(function () {
135
            // make regular flush before other shutdown functions, which allows session data collection and so on
136
            $this->flush();
137
            // make sure log entries written by shutdown functions are also flushed
138
            // ensure "flush()" is called last when there are multiple shutdown functions
139
            register_shutdown_function([$this, 'flush'], true);
140 44
        });
141
    }
142
143
    /**
144
     * Logs a message with the given type and category.
145
     * If [[traceLevel]] is greater than 0, additional call stack information about
146
     * the application code will be logged as well.
147
     * @param string|array $message the message to be logged. This can be a simple string or a more
148
     * complex data structure that will be handled by a [[Target|log target]].
149
     * @param int $level the level of the message. This must be one of the following:
150
     * `Logger::LEVEL_ERROR`, `Logger::LEVEL_WARNING`, `Logger::LEVEL_INFO`, `Logger::LEVEL_TRACE`, `Logger::LEVEL_PROFILE`,
151
     * `Logger::LEVEL_PROFILE_BEGIN`, `Logger::LEVEL_PROFILE_END`.
152
     * @param string $category the category of the message.
153
     */
154 2534
    public function log($message, $level, $category = 'application')
155
    {
156 2534
        $time = microtime(true);
157 2534
        $traces = [];
158 2534
        if ($this->traceLevel > 0) {
159 1
            $count = 0;
160 1
            $ts = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
161 1
            array_pop($ts); // remove the last trace since it would be the entry script, not very useful
162 1
            foreach ($ts as $trace) {
163 1
                if (isset($trace['file'], $trace['line']) && strpos($trace['file'], YII2_PATH) !== 0) {
164 1
                    unset($trace['object'], $trace['args']);
165 1
                    $traces[] = $trace;
166 1
                    if (++$count >= $this->traceLevel) {
167 1
                        break;
168
                    }
169
                }
170
            }
171
        }
172 2534
        $data = [$message, $level, $category, $time, $traces, memory_get_usage()];
173 2534
        if ($this->profilingAware && in_array($level, [self::LEVEL_PROFILE_BEGIN, self::LEVEL_PROFILE_END])) {
174 2
            $this->messages[($level == self::LEVEL_PROFILE_BEGIN ? 'begin-' : 'end-') . md5(json_encode($message))] = $data;
175
        } else {
176 2534
            $this->messages[] = $data;
177
        }
178
179 2534
        if ($this->flushInterval > 0 && count($this->messages) >= $this->flushInterval) {
180 436
            $this->flush();
181
        }
182
    }
183
184
    /**
185
     * Flushes log messages from memory to targets.
186
     * @param bool $final whether this is a final call during a request.
187
     */
188 445
    public function flush($final = false)
189
    {
190 445
        if ($this->profilingAware) {
191 2
            $keep = [];
192 2
            $messages = [];
193 2
            foreach ($this->messages as $index => $message) {
194 2
                if (is_int($index)) {
195 2
                    $messages[] = $message;
196
                } else {
197 2
                    if (strncmp($index, 'begin-', 6) === 0) {
198 2
                        $oppositeProfile = 'end-' . substr($index, 6);
199
                    } else {
200 2
                        $oppositeProfile = 'begin-' . substr($index, 4);
201
                    }
202 2
                    if (array_key_exists($oppositeProfile, $this->messages)) {
203 1
                        $messages[] = $message;
204
                    } else {
205 2
                        $keep[$index] = $message;
206
                    }
207
                }
208
            }
209 2
            if ($this->flushInterval > 0 && count($keep) >= $this->flushInterval) {
210 1
                $this->messages = [];
211 1
                $this->log(
212 1
                    'Number of dangling profiling block messages reached flushInterval value and therefore these were flushed. Please consider setting higher flushInterval value or making profiling blocks shorter.',
213 1
                    self::LEVEL_WARNING
214 1
                );
215 1
                $messages = array_merge($messages, array_values($keep));
216
            } else {
217 2
                $this->messages = $keep;
218
            }
219
        } else {
220 443
            $messages = $this->messages;
221 443
            $this->messages = [];
222
        }
223
224 445
        if ($this->dispatcher instanceof Dispatcher) {
0 ignored issues
show
$this->dispatcher is always a sub-type of yii\log\Dispatcher.
Loading history...
225 444
            $this->dispatcher->dispatch($messages, $final);
226
        }
227
    }
228
229
    /**
230
     * Returns the total elapsed time since the start of the current request.
231
     * This method calculates the difference between now and the timestamp
232
     * defined by constant `YII_BEGIN_TIME` which is evaluated at the beginning
233
     * of [[\yii\BaseYii]] class file.
234
     * @return float the total elapsed time in seconds for current request.
235
     */
236 1
    public function getElapsedTime()
237
    {
238 1
        return microtime(true) - YII_BEGIN_TIME;
239
    }
240
241
    /**
242
     * Returns the profiling results.
243
     *
244
     * By default, all profiling results will be returned. You may provide
245
     * `$categories` and `$excludeCategories` as parameters to retrieve the
246
     * results that you are interested in.
247
     *
248
     * @param array $categories list of categories that you are interested in.
249
     * You can use an asterisk at the end of a category to do a prefix match.
250
     * For example, 'yii\db\*' will match categories starting with 'yii\db\',
251
     * such as 'yii\db\Connection'.
252
     * @param array $excludeCategories list of categories that you want to exclude
253
     * @return array the profiling results. Each element is an array consisting of these elements:
254
     * `info`, `category`, `timestamp`, `trace`, `level`, `duration`, `memory`, `memoryDiff`.
255
     * The `memory` and `memoryDiff` values are available since version 2.0.11.
256
     */
257 10
    public function getProfiling($categories = [], $excludeCategories = [])
258
    {
259 10
        $timings = $this->calculateTimings($this->messages);
260 10
        if (empty($categories) && empty($excludeCategories)) {
261 7
            return $timings;
262
        }
263
264 3
        foreach ($timings as $outerIndex => $outerTimingItem) {
265 3
            $currentIndex = $outerIndex;
266 3
            $matched = empty($categories);
267 3
            foreach ($categories as $category) {
268 3
                $prefix = rtrim($category, '*');
269
                if (
270 3
                    ($outerTimingItem['category'] === $category || $prefix !== $category)
271 3
                    && strpos($outerTimingItem['category'], $prefix) === 0
272
                ) {
273 2
                    $matched = true;
274 2
                    break;
275
                }
276
            }
277
278 3
            if ($matched) {
279 2
                foreach ($excludeCategories as $category) {
280 1
                    $prefix = rtrim($category, '*');
281 1
                    foreach ($timings as $innerIndex => $innerTimingItem) {
282 1
                        $currentIndex = $innerIndex;
283
                        if (
284 1
                            ($innerTimingItem['category'] === $category || $prefix !== $category)
285 1
                            && strpos($innerTimingItem['category'], $prefix) === 0
286
                        ) {
287 1
                            $matched = false;
288 1
                            break;
289
                        }
290
                    }
291
                }
292
            }
293
294 3
            if (!$matched) {
295 3
                unset($timings[$currentIndex]);
296
            }
297
        }
298
299 3
        return array_values($timings);
300
    }
301
302
    /**
303
     * Returns the statistical results of DB queries.
304
     * The results returned include the number of SQL statements executed and
305
     * the total time spent.
306
     * @return array the first element indicates the number of SQL statements executed,
307
     * and the second element the total time spent in SQL execution.
308
     */
309 1
    public function getDbProfiling()
310
    {
311 1
        $timings = $this->getProfiling($this->dbEventNames);
312 1
        $count = count($timings);
313 1
        $time = 0;
314 1
        foreach ($timings as $timing) {
315 1
            $time += $timing['duration'];
316
        }
317
318 1
        return [$count, $time];
319
    }
320
321
    /**
322
     * Calculates the elapsed time for the given log messages.
323
     * @param array $messages the log messages obtained from profiling
324
     * @return array timings. Each element is an array consisting of these elements:
325
     * `info`, `category`, `timestamp`, `trace`, `level`, `duration`, `memory`, `memoryDiff`.
326
     * The `memory` and `memoryDiff` values are available since version 2.0.11.
327
     */
328 11
    public function calculateTimings($messages)
329
    {
330 11
        $timings = [];
331 11
        $stack = [];
332
333 11
        foreach ($messages as $i => $log) {
334 10
            list($token, $level, $category, $timestamp, $traces) = $log;
335 10
            $memory = isset($log[5]) ? $log[5] : 0;
336 10
            $log[6] = $i;
337 10
            $hash = md5(json_encode($token));
338 10
            if ($level == self::LEVEL_PROFILE_BEGIN) {
339 4
                $stack[$hash] = $log;
340 10
            } elseif ($level == self::LEVEL_PROFILE_END) {
341 9
                if (isset($stack[$hash])) {
342 4
                    $timings[$stack[$hash][6]] = [
343 4
                        'info' => $stack[$hash][0],
344 4
                        'category' => $stack[$hash][2],
345 4
                        'timestamp' => $stack[$hash][3],
346 4
                        'trace' => $stack[$hash][4],
347 4
                        'level' => count($stack) - 1,
348 4
                        'duration' => $timestamp - $stack[$hash][3],
349 4
                        'memory' => $memory,
350 4
                        'memoryDiff' => $memory - (isset($stack[$hash][5]) ? $stack[$hash][5] : 0),
351 4
                    ];
352 4
                    unset($stack[$hash]);
353
                }
354
            }
355
        }
356
357 11
        ksort($timings);
358
359 11
        return array_values($timings);
360
    }
361
362
363
    /**
364
     * Returns the text display of the specified level.
365
     * @param int $level the message level, e.g. [[LEVEL_ERROR]], [[LEVEL_WARNING]].
366
     * @return string the text display of the level
367
     */
368 3
    public static function getLevelName($level)
369
    {
370 3
        static $levels = [
371 3
            self::LEVEL_ERROR => 'error',
372 3
            self::LEVEL_WARNING => 'warning',
373 3
            self::LEVEL_INFO => 'info',
374 3
            self::LEVEL_TRACE => 'trace',
375 3
            self::LEVEL_PROFILE_BEGIN => 'profile begin',
376 3
            self::LEVEL_PROFILE_END => 'profile end',
377 3
            self::LEVEL_PROFILE => 'profile',
378 3
        ];
379
380 3
        return isset($levels[$level]) ? $levels[$level] : 'unknown';
381
    }
382
}
383