Passed
Push — master ( fd1468...c654ef )
by Alexander
02:13
created

Logger::setTraceLevel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Log;
6
7
use InvalidArgumentException;
8
use Psr\Log\LoggerInterface;
9
use Psr\Log\LoggerTrait;
10
use Psr\Log\LogLevel;
11
use Stringable;
12
use Throwable;
13
use Yiisoft\Log\Message\CategoryFilter;
14
15
use function array_filter;
16
use function count;
17
use function debug_backtrace;
18
use function gettype;
19
use function get_class;
20
use function implode;
21
use function in_array;
22
use function is_string;
23
use function memory_get_usage;
24
use function microtime;
25
use function register_shutdown_function;
26
use function sprintf;
27
28
/**
29
 * Logger records logged messages in memory and sends them to different targets according to {@see Logger::$targets}.
30
 *
31
 * You can call the method {@see Logger::log()} to record a single log message.
32
 *
33
 * For more details and usage information on Logger,
34
 * see [PSR-3 specification](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md).
35
 *
36
 * When the application ends or {@see Logger::$flushInterval} is reached, Logger will call {@see Logger::flush()}
37
 * to send logged messages to different log targets, such as file or email according to the {@see Logger::$targets}.
38
 */
39
final class Logger implements LoggerInterface
40
{
41
    use LoggerTrait;
42
43
    /**
44
     * The list of log message levels. See {@see LogLevel} constants for valid level names.
45
     */
46
    private const LEVELS = [
47
        LogLevel::EMERGENCY,
48
        LogLevel::ALERT,
49
        LogLevel::CRITICAL,
50
        LogLevel::ERROR,
51
        LogLevel::WARNING,
52
        LogLevel::NOTICE,
53
        LogLevel::INFO,
54
        LogLevel::DEBUG,
55
    ];
56
57
    /**
58
     * @var Message[] The log messages.
59
     */
60
    private array $messages = [];
61
62
    /**
63
     * @var Target[] the log targets. Each array element represents a single {@see \Yiisoft\Log\Target} instance.
64
     */
65
    private array $targets = [];
66
67
    /**
68
     * @var string[] Array of paths to exclude from tracing when tracing is enabled with {@see Logger::setTraceLevel()}.
69
     */
70
    private array $excludedTracePaths = [];
71
72
    /**
73
     * @var int How many log messages should be logged before they are flushed from memory and sent to targets.
74
     *
75
     * Defaults to 1000, meaning the {@see Logger::flush()} method will be invoked once every 1000 messages logged.
76
     * Set this property to be 0 if you don't want to flush messages until the application terminates.
77
     * This property mainly affects how much memory will be taken by the logged messages.
78
     * A smaller value means less memory, but will increase the execution
79
     * time due to the overhead of {@see Logger::flush()}.
80
     */
81
    private int $flushInterval = 1000;
82
83
    /**
84
     * @var int How much call stack information (file name and line number) should be logged for each log message.
85
     *
86
     * If it is greater than 0, at most that number of call stacks will be logged.
87
     * Note that only application call stacks are counted.
88
     */
89
    private int $traceLevel = 0;
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 56
    public function __construct(array $targets = [])
97
    {
98 56
        $this->setTargets($targets);
99
100 56
        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
        });
107
    }
108
109
    /**
110
     * Returns the text display of the specified level.
111
     *
112
     * @param mixed $level The message level, e.g. {@see LogLevel::ERROR}, {@see LogLevel::WARNING}.
113
     *
114
     * @throws \Psr\Log\InvalidArgumentException for invalid log message level.
115
     *
116
     * @return string The text display of the level.
117
     */
118 149
    public static function validateLevel(mixed $level): string
119
    {
120 149
        if (!is_string($level)) {
121 13
            throw new \Psr\Log\InvalidArgumentException(sprintf(
122
                'The log message level must be a string, %s provided.',
123 13
                gettype($level)
124
            ));
125
        }
126
127 136
        if (!in_array($level, self::LEVELS, true)) {
128 2
            throw new \Psr\Log\InvalidArgumentException(sprintf(
129
                'Invalid log message level "%s" provided. The following values are supported: "%s".',
130
                $level,
131 2
                implode('", "', self::LEVELS)
132
            ));
133
        }
134
135 134
        return $level;
136
    }
137
138
    /**
139
     * @return Target[] The log targets. Each array element represents a single {@see \Yiisoft\Log\Target} instance.
140
     */
141 1
    public function getTargets(): array
142
    {
143 1
        return $this->targets;
144
    }
145
146 31
    public function log(mixed $level, string|Stringable $message, array $context = []): void
147
    {
148 31
        $context['time'] ??= microtime(true);
149 31
        $context['trace'] ??= $this->collectTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));
150 31
        $context['memory'] ??= memory_get_usage();
151 31
        $context['category'] ??= CategoryFilter::DEFAULT;
152
153 31
        $this->messages[] = new Message($level, $message, $context);
154
155 31
        if ($this->flushInterval > 0 && count($this->messages) >= $this->flushInterval) {
156 21
            $this->flush();
157
        }
158
    }
159
160
    /**
161
     * Flushes log messages from memory to targets.
162
     *
163
     * @param bool $final Whether this is a final call during a request.
164
     */
165 23
    public function flush(bool $final = false): void
166
    {
167 23
        $messages = $this->messages;
168
        // https://github.com/yiisoft/yii2/issues/5619
169
        // new messages could be logged while the existing ones are being handled by targets
170 23
        $this->messages = [];
171
172 23
        $this->dispatch($messages, $final);
173
    }
174
175
    /**
176
     * Sets how many log messages should be logged before they are flushed from memory and sent to targets.
177
     *
178
     * @param int $flushInterval The number of messages to accumulate before flushing.
179
     *
180
     * @return self
181
     *
182
     * @see Logger::$flushInterval
183
     */
184 21
    public function setFlushInterval(int $flushInterval): self
185
    {
186 21
        $this->flushInterval = $flushInterval;
187 21
        return $this;
188
    }
189
190
    /**
191
     * Sets how much call stack information (file name and line number) should be logged for each log message.
192
     *
193
     * @param int $traceLevel The number of call stack information.
194
     *
195
     * @return self
196
     *
197
     * @see Logger::$traceLevel
198
     */
199 2
    public function setTraceLevel(int $traceLevel): self
200
    {
201 2
        $this->traceLevel = $traceLevel;
202 2
        return $this;
203
    }
204
205
    /**
206
     * Sets an array of paths to exclude from tracing when tracing is enabled with {@see Logger::setTraceLevel()}.
207
     *
208
     * @param array $excludedTracePaths The paths to exclude from tracing.
209
     *
210
     * @throws InvalidArgumentException for non-string values.
211
     *
212
     * @return self
213
     *
214
     * @see Logger::$excludedTracePaths
215
     */
216 8
    public function setExcludedTracePaths(array $excludedTracePaths): self
217
    {
218 8
        foreach ($excludedTracePaths as $excludedTracePath) {
219 8
            if (!is_string($excludedTracePath)) {
220 7
                throw new InvalidArgumentException(sprintf(
221
                    'The trace path must be a string, %s received.',
222 7
                    gettype($excludedTracePath)
223
                ));
224
            }
225
        }
226
227 1
        $this->excludedTracePaths = $excludedTracePaths;
228 1
        return $this;
229
    }
230
231
    /**
232
     * Sets a target to {@see Logger::$targets}.
233
     *
234
     * @param array $targets The log targets. Each array element represents a single {@see \Yiisoft\Log\Target}
235
     * instance or the configuration for creating the log target instance.
236
     *
237
     * @throws InvalidArgumentException for non-instance Target.
238
     */
239 56
    private function setTargets(array $targets): void
240
    {
241 56
        foreach ($targets as $target) {
242 56
            if (!($target instanceof Target)) {
243 8
                throw new InvalidArgumentException('You must provide an instance of \Yiisoft\Log\Target.');
244
            }
245
        }
246
247 56
        $this->targets = $targets;
248
    }
249
250
    /**
251
     * Dispatches the logged messages to {@see Logger::$targets}.
252
     *
253
     * @param Message[] $messages The log messages.
254
     * @param bool $final Whether this method is called at the end of the current application.
255
     */
256 26
    private function dispatch(array $messages, bool $final): void
257
    {
258 26
        $targetErrors = [];
259
260 26
        foreach ($this->targets as $target) {
261 26
            if ($target->isEnabled()) {
262
                try {
263 25
                    $target->collect($messages, $final);
264 1
                } catch (Throwable $e) {
265 1
                    $target->disable();
266 1
                    $targetErrors[] = new Message(
267
                        LogLevel::WARNING,
268 1
                        'Unable to send log via ' . get_class($target) . ': ' . get_class($e) . ': ' . $e->getMessage(),
269 1
                        ['time' => microtime(true), 'exception' => $e],
270
                    );
271
                }
272
            }
273
        }
274
275 26
        if (!empty($targetErrors)) {
276 1
            $this->dispatch($targetErrors, true);
277
        }
278
    }
279
280
    /**
281
     * Collects a trace when tracing is enabled with {@see Logger::setTraceLevel()}.
282
     *
283
     * @param array $backtrace The list of call stack information.
284
     *
285
     * @return array Collected a list of call stack information.
286
     */
287 31
    private function collectTrace(array $backtrace): array
288
    {
289 31
        $traces = [];
290
291 31
        if ($this->traceLevel > 0) {
292 2
            $count = 0;
293
294 2
            foreach ($backtrace as $trace) {
295 2
                if (isset($trace['file'], $trace['line'])) {
296 2
                    $excludedMatch = array_filter($this->excludedTracePaths, static function ($path) use ($trace) {
297 1
                        return str_contains($trace['file'], $path);
298
                    });
299
300 2
                    if (empty($excludedMatch)) {
301 2
                        unset($trace['object'], $trace['args']);
302 2
                        $traces[] = $trace;
303 2
                        if (++$count >= $this->traceLevel) {
304 1
                            break;
305
                        }
306
                    }
307
                }
308
            }
309
        }
310
311 31
        return $traces;
312
    }
313
}
314