Passed
Pull Request — master (#46)
by Evgeniy
02:10
created

Logger::collectTrace()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6.0106

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 13
nc 6
nop 1
dl 0
loc 22
ccs 14
cts 15
cp 0.9333
crap 6.0106
rs 9.2222
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Log;
6
7
use Exception;
8
use Psr\Log\InvalidArgumentException;
9
use Psr\Log\LoggerInterface;
10
use Psr\Log\LoggerTrait;
11
use Psr\Log\LogLevel;
12
use Throwable;
13
use Yiisoft\VarDumper\VarDumper;
14
15
use function array_filter;
16
use function count;
17
use function debug_backtrace;
18
use function get_class;
19
use function is_scalar;
20
use function is_string;
21
use function memory_get_usage;
22
use function method_exists;
23
use function preg_replace_callback;
24
use function register_shutdown_function;
25
use function strpos;
26
27
/**
28
 * Logger records logged messages in memory and sends them to different targets according to {@see Logger::$targets}.
29
 *
30
 * You can call the method {@see Logger::log()} to record a single log message.
31
 *
32
 * For more details and usage information on Logger,
33
 * see [PSR-3 specification](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md).
34
 *
35
 * When the application ends or {@see Logger::$flushInterval} is reached, Logger will call {@see Logger::flush()}
36
 * to send logged messages to different log targets, such as file or email according to the {@see Logger::$targets}.
37
 */
38
class Logger implements LoggerInterface
39
{
40
    use LoggerTrait;
41
42
    /**
43
     * @var array logged messages. This property is managed by {@see Logger::log()} and {@see Logger::flush()}.
44
     * Each log message is of the following structure:
45
     *
46
     * ```
47
     * [
48
     *   [0] => level (string)
49
     *   [1] => message (mixed, can be a string or some complex data, such as an exception object)
50
     *   [2] => context (array)
51
     * ]
52
     * ```
53
     *
54
     * Message context has a following keys:
55
     *
56
     * - category: string, message category.
57
     * - time: float, message timestamp obtained by microtime(true).
58
     * - trace: array, debug backtrace, contains the application code call stacks.
59
     * - memory: int, memory usage in bytes, obtained by `memory_get_usage()`.
60
     */
61
    private array $messages = [];
62
63
    /**
64
     * @var int how many messages should be logged before they are flushed from memory and sent to targets.
65
     * Defaults to 1000, meaning the {@see Logger::flush()} method will be invoked once every 1000 messages logged.
66
     * Set this property to be 0 if you don't want to flush messages until the application terminates.
67
     * This property mainly affects how much memory will be taken by the logged messages.
68
     * A smaller value means less memory, but will increase the execution
69
     * time due to the overhead of {@see Logger::flush()}.
70
     */
71
    private int $flushInterval = 1000;
72
73
    /**
74
     * @var int how much call stack information (file name and line number) should be logged for each message.
75
     * If it is greater than 0, at most that number of call stacks will be logged. Note that only application
76
     * call stacks are counted.
77
     */
78
    private int $traceLevel = 0;
79
80
    /**
81
     * @var array An array of paths to exclude from the trace when tracing is enabled using
82
     * {@see Logger::setTraceLevel()}.
83
     */
84
    private array $excludedTracePaths = [];
85
86
    /**
87
     * @var Target[] the log targets. Each array element represents a single {@see \Yiisoft\Log\Target} instance
88
     */
89
    private array $targets = [];
90
91
    /**
92
     * Initializes the logger by registering {@see Logger::flush()} as a shutdown function.
93
     *
94
     * @param Target[] $targets the log targets.
95
     */
96 21
    public function __construct(array $targets = [])
97
    {
98 21
        $this->setTargets($targets);
99
100 21
        register_shutdown_function(function () {
101
            // make regular flush before other shutdown functions, which allows session data collection and so on
102
            $this->flush();
103
            // make sure log entries written by shutdown functions are also flushed
104
            // ensure "flush()" is called last when there are multiple shutdown functions
105
            register_shutdown_function([$this, 'flush'], true);
106 21
        });
107 21
    }
108
109
    /**
110
     * @return Target[] the log targets. Each array element represents a single {@see \Yiisoft\Log\Target} instance.
111
     */
112 21
    public function getTargets(): array
113
    {
114 21
        return $this->targets;
115
    }
116
117
    /**
118
     * @param int|string $name string name or integer index
119
     * @return Target|null
120
     */
121
    public function getTarget($name): ?Target
122
    {
123
        return $this->getTargets()[$name] ?? null;
124
    }
125
126
    /**
127
     * @param array $targets the log targets. Each array element represents a single {@see \Yiisoft\Log\Target}
128
     * instance or the configuration for creating the log target instance.
129
     */
130 22
    public function setTargets(array $targets): void
131
    {
132 22
        foreach ($targets as $target) {
133 21
            if (!$target instanceof Target) {
134
                throw new InvalidArgumentException('You must provide an instance of \Yiisoft\Log\Target.');
135
            }
136
        }
137 22
        $this->targets = $targets;
138 22
    }
139
140
    /**
141
     * Adds extra target to {@see Logger::$targets}.
142
     * @param Target $target the log target instance.
143
     * @param string|null $name array key to be used to store target, if `null` is given target will be append
144
     * to the end of the array by natural integer key.
145
     */
146 1
    public function addTarget(Target $target, string $name = null): void
147
    {
148 1
        if ($name === null) {
149 1
            $this->targets[] = $target;
150
        } else {
151 1
            $this->targets[$name] = $target;
152
        }
153 1
    }
154
155 24
    public function log($level, $message, array $context = []): void
156
    {
157 24
        if (($message instanceof Throwable) && !isset($context['exception'])) {
158
            // exceptions are string-convertible, thus should be passed as it is to the logger
159
            // if exception instance is given to produce a stack trace, it MUST be in a key named "exception".
160
            $context['exception'] = $message;
161
        }
162
163 24
        $message = static::prepareMessage($message);
164
165 24
        $context['time'] ??= microtime(true);
166 24
        $context['trace'] ??= $this->collectTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));
167 24
        $context['memory'] ??= memory_get_usage();
168 24
        $context['category'] ??= Target::DEFAULT_CATEGORY;
169
170 24
        $message = static::parseMessage($message, $context);
171
172 24
        $this->messages[] = [$level, $message, $context];
173
174 24
        if ($this->flushInterval > 0 && count($this->messages) >= $this->flushInterval) {
175 21
            $this->flush();
176
        }
177 24
    }
178
179
    /**
180
     * Flushes log messages from memory to targets.
181
     * @param bool $final whether this is a final call during a request.
182
     */
183 22
    public function flush(bool $final = false): void
184
    {
185 22
        $messages = $this->messages;
186
        // https://github.com/yiisoft/yii2/issues/5619
187
        // new messages could be logged while the existing ones are being handled by targets
188 22
        $this->messages = [];
189
190 22
        $this->dispatch($messages, $final);
191 22
    }
192
193
    /**
194
     * Dispatches the logged messages to {@see Logger::$targets}.
195
     * @param array $messages the logged messages
196
     * @param bool $final whether this method is called at the end of the current application
197
     */
198 23
    protected function dispatch(array $messages, bool $final): void
199
    {
200 23
        $targetErrors = [];
201 23
        foreach ($this->getTargets() as $target) {
202 23
            if ($target->isEnabled()) {
203
                try {
204 22
                    $target->collect($messages, $final);
205 1
                } catch (Exception $e) {
206 1
                    $target->disable();
207 1
                    $targetErrors[] = [
208 1
                        'Unable to send log via ' . get_class($target) . ': ' . get_class($e) . ': ' . $e->getMessage(),
209
                        LogLevel::WARNING,
210
                        __METHOD__,
211 1
                        microtime(true),
212
                        [],
213
                    ];
214
                }
215
            }
216
        }
217
218 23
        if (!empty($targetErrors)) {
219 1
            $this->dispatch($targetErrors, true);
220
        }
221 23
    }
222
223
    /**
224
     * Prepares message for logging.
225
     * @param mixed $message
226
     * @return string
227
     */
228 21
    protected static function prepareMessage($message): string
229
    {
230 21
        if (method_exists($message, '__toString')) {
231
            return (string) $message;
232
        }
233
234 21
        if (is_scalar($message)) {
235 21
            return (string) $message;
236
        }
237
238
        return VarDumper::create($message)->export();
239
    }
240
241
    /**
242
     * Parses log message resolving placeholders in the form: '{foo}', where foo
243
     * will be replaced by the context data in key "foo".
244
     * @param string $message log message.
245
     * @param array $context message context.
246
     * @return string parsed message.
247
     */
248 24
    protected static function parseMessage(string $message, array $context): string
249
    {
250 24
        return preg_replace_callback('/{([\w.]+)}/', static function (array $matches) use ($context) {
251 2
            $placeholderName = $matches[1];
252 2
            if (isset($context[$placeholderName])) {
253 1
                return (string) $context[$placeholderName];
254
            }
255 1
            return $matches[0];
256 24
        }, $message);
257
    }
258
259
    /**
260
     * Returns the text display of the specified level.
261
     * @param mixed $level the message level, e.g. {@see LogLevel::ERROR}, {@see LogLevel::WARNING}.
262
     * @return string the text display of the level
263
     */
264 3
    public static function getLevelName($level): string
265
    {
266 3
        if (is_string($level)) {
267 3
            return $level;
268
        }
269 1
        return 'unknown';
270
    }
271
272
    public function getFlushInterval(): int
273
    {
274
        return $this->flushInterval;
275
    }
276
277 20
    public function setFlushInterval(int $flushInterval): self
278
    {
279 20
        $this->flushInterval = $flushInterval;
280 20
        return $this;
281
    }
282
283
    public function getTraceLevel(): int
284
    {
285
        return $this->traceLevel;
286
    }
287
288 1
    public function setTraceLevel(int $traceLevel): self
289
    {
290 1
        $this->traceLevel = $traceLevel;
291 1
        return $this;
292
    }
293
294 1
    public function setExcludedTracePaths(array $excludedTracePaths): self
295
    {
296 1
        $this->excludedTracePaths = $excludedTracePaths;
297 1
        return $this;
298
    }
299
300 21
    private function collectTrace(array $backtrace): array
301
    {
302 21
        $traces = [];
303 21
        if ($this->traceLevel > 0) {
304 1
            $count = 0;
305 1
            foreach ($backtrace as $trace) {
306 1
                if (isset($trace['file'], $trace['line'])) {
307 1
                    $excludedMatch = array_filter($this->excludedTracePaths, static function ($path) use ($trace) {
308 1
                        return strpos($trace['file'], $path) !== false;
309 1
                    });
310
311 1
                    if (empty($excludedMatch)) {
312 1
                        unset($trace['object'], $trace['args']);
313 1
                        $traces[] = $trace;
314 1
                        if (++$count >= $this->traceLevel) {
315
                            break;
316
                        }
317
                    }
318
                }
319
            }
320
        }
321 21
        return $traces;
322
    }
323
}
324