Passed
Push — master ( a8cd64...c52ac9 )
by Alexander
02:12
created

Logger::getElapsedTime()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
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
     * Returns the text display of the specified level.
111
     * @param mixed $level the message level, e.g. {@see LogLevel::ERROR}, {@see LogLevel::WARNING}.
112
     * @return string the text display of the level
113
     */
114 3
    public static function getLevelName($level): string
115
    {
116 3
        if (is_string($level)) {
117 3
            return $level;
118
        }
119 1
        return 'unknown';
120
    }
121
122
    /**
123
     * @return Target[] the log targets. Each array element represents a single {@see \Yiisoft\Log\Target} instance.
124
     */
125 21
    public function getTargets(): array
126
    {
127 21
        return $this->targets;
128
    }
129
130
    /**
131
     * @param int|string $name string name or integer index
132
     * @return Target|null
133
     */
134
    public function getTarget($name): ?Target
135
    {
136
        return $this->getTargets()[$name] ?? null;
137
    }
138
139
    /**
140
     * @param array $targets the log targets. Each array element represents a single {@see \Yiisoft\Log\Target}
141
     * instance or the configuration for creating the log target instance.
142
     */
143 22
    public function setTargets(array $targets): void
144
    {
145 22
        foreach ($targets as $target) {
146 21
            if (!$target instanceof Target) {
147
                throw new InvalidArgumentException('You must provide an instance of \Yiisoft\Log\Target.');
148
            }
149
        }
150 22
        $this->targets = $targets;
151 22
    }
152
153
    /**
154
     * Adds extra target to {@see Logger::$targets}.
155
     * @param Target $target the log target instance.
156
     * @param string|null $name array key to be used to store target, if `null` is given target will be append
157
     * to the end of the array by natural integer key.
158
     */
159 1
    public function addTarget(Target $target, string $name = null): void
160
    {
161 1
        if ($name === null) {
162 1
            $this->targets[] = $target;
163
        } else {
164 1
            $this->targets[$name] = $target;
165
        }
166 1
    }
167
168 24
    public function log($level, $message, array $context = []): void
169
    {
170 24
        if (($message instanceof Throwable) && !isset($context['exception'])) {
171
            // exceptions are string-convertible, thus should be passed as it is to the logger
172
            // if exception instance is given to produce a stack trace, it MUST be in a key named "exception".
173
            $context['exception'] = $message;
174
        }
175
176 24
        $message = $this->prepareMessage($message);
177
178 24
        $context['time'] ??= microtime(true);
179 24
        $context['trace'] ??= $this->collectTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));
180 24
        $context['memory'] ??= memory_get_usage();
181 24
        $context['category'] ??= Target::DEFAULT_CATEGORY;
182
183 24
        $message = $this->parseMessage($message, $context);
184
185 24
        $this->messages[] = [$level, $message, $context];
186
187 24
        if ($this->flushInterval > 0 && count($this->messages) >= $this->flushInterval) {
188 21
            $this->flush();
189
        }
190 24
    }
191
192
    /**
193
     * Flushes log messages from memory to targets.
194
     * @param bool $final whether this is a final call during a request.
195
     */
196 22
    public function flush(bool $final = false): void
197
    {
198 22
        $messages = $this->messages;
199
        // https://github.com/yiisoft/yii2/issues/5619
200
        // new messages could be logged while the existing ones are being handled by targets
201 22
        $this->messages = [];
202
203 22
        $this->dispatch($messages, $final);
204 22
    }
205
206
    public function getFlushInterval(): int
207
    {
208
        return $this->flushInterval;
209
    }
210
211 20
    public function setFlushInterval(int $flushInterval): self
212
    {
213 20
        $this->flushInterval = $flushInterval;
214 20
        return $this;
215
    }
216
217
    public function getTraceLevel(): int
218
    {
219
        return $this->traceLevel;
220
    }
221
222 1
    public function setTraceLevel(int $traceLevel): self
223
    {
224 1
        $this->traceLevel = $traceLevel;
225 1
        return $this;
226
    }
227
228 1
    public function setExcludedTracePaths(array $excludedTracePaths): self
229
    {
230 1
        $this->excludedTracePaths = $excludedTracePaths;
231 1
        return $this;
232
    }
233
234
    /**
235
     * Dispatches the logged messages to {@see Logger::$targets}.
236
     * @param array $messages the logged messages
237
     * @param bool $final whether this method is called at the end of the current application
238
     */
239 23
    protected function dispatch(array $messages, bool $final): void
240
    {
241 23
        $targetErrors = [];
242 23
        foreach ($this->getTargets() as $target) {
243 23
            if ($target->isEnabled()) {
244
                try {
245 22
                    $target->collect($messages, $final);
246 1
                } catch (Exception $e) {
247 1
                    $target->disable();
248 1
                    $targetErrors[] = [
249 1
                        'Unable to send log via ' . get_class($target) . ': ' . get_class($e) . ': ' . $e->getMessage(),
250
                        LogLevel::WARNING,
251
                        __METHOD__,
252 1
                        microtime(true),
253
                        [],
254
                    ];
255
                }
256
            }
257
        }
258
259 23
        if (!empty($targetErrors)) {
260 1
            $this->dispatch($targetErrors, true);
261
        }
262 23
    }
263
264
    /**
265
     * Prepares message for logging.
266
     * @param mixed $message
267
     * @return string
268
     */
269 21
    protected function prepareMessage($message): string
270
    {
271 21
        if (method_exists($message, '__toString')) {
272
            return (string) $message;
273
        }
274
275 21
        if (is_scalar($message)) {
276 21
            return (string) $message;
277
        }
278
279
        return VarDumper::create($message)->export();
280
    }
281
282
    /**
283
     * Parses log message resolving placeholders in the form: '{foo}', where foo
284
     * will be replaced by the context data in key "foo".
285
     * @param string $message log message.
286
     * @param array $context message context.
287
     * @return string parsed message.
288
     */
289 24
    protected function parseMessage(string $message, array $context): string
290
    {
291 24
        return preg_replace_callback('/{([\w.]+)}/', static function (array $matches) use ($context) {
292 2
            $placeholderName = $matches[1];
293 2
            if (isset($context[$placeholderName])) {
294 1
                return (string) $context[$placeholderName];
295
            }
296 1
            return $matches[0];
297 24
        }, $message);
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