forked from Seldaek/monolog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNormalizerFormatter.php
357 lines (299 loc) · 10.1 KB
/
NormalizerFormatter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Monolog\DateTimeImmutable;
use Monolog\Utils;
use Throwable;
use Monolog\LogRecord;
/**
* Normalizes incoming records to remove objects/resources so it's easier to dump to various targets
*
* @author Jordi Boggiano <[email protected]>
*/
class NormalizerFormatter implements FormatterInterface
{
public const SIMPLE_DATE = "Y-m-d\TH:i:sP";
protected string $dateFormat;
protected int $maxNormalizeDepth = 9;
protected int $maxNormalizeItemCount = 1000;
private int $jsonEncodeOptions = Utils::DEFAULT_JSON_FLAGS;
protected string $basePath = '';
/**
* @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format
* @throws \RuntimeException If the function json_encode does not exist
*/
public function __construct(?string $dateFormat = null)
{
$this->dateFormat = null === $dateFormat ? static::SIMPLE_DATE : $dateFormat;
if (!\function_exists('json_encode')) {
throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s NormalizerFormatter');
}
}
/**
* @inheritDoc
*/
public function format(LogRecord $record)
{
return $this->normalizeRecord($record);
}
/**
* Normalize an arbitrary value to a scalar|array|null
*
* @return null|scalar|array<mixed[]|scalar|null>
*/
public function normalizeValue(mixed $data): mixed
{
return $this->normalize($data);
}
/**
* @inheritDoc
*/
public function formatBatch(array $records)
{
foreach ($records as $key => $record) {
$records[$key] = $this->format($record);
}
return $records;
}
public function getDateFormat(): string
{
return $this->dateFormat;
}
/**
* @return $this
*/
public function setDateFormat(string $dateFormat): self
{
$this->dateFormat = $dateFormat;
return $this;
}
/**
* The maximum number of normalization levels to go through
*/
public function getMaxNormalizeDepth(): int
{
return $this->maxNormalizeDepth;
}
/**
* @return $this
*/
public function setMaxNormalizeDepth(int $maxNormalizeDepth): self
{
$this->maxNormalizeDepth = $maxNormalizeDepth;
return $this;
}
/**
* The maximum number of items to normalize per level
*/
public function getMaxNormalizeItemCount(): int
{
return $this->maxNormalizeItemCount;
}
/**
* @return $this
*/
public function setMaxNormalizeItemCount(int $maxNormalizeItemCount): self
{
$this->maxNormalizeItemCount = $maxNormalizeItemCount;
return $this;
}
/**
* Enables `json_encode` pretty print.
*
* @return $this
*/
public function setJsonPrettyPrint(bool $enable): self
{
if ($enable) {
$this->jsonEncodeOptions |= JSON_PRETTY_PRINT;
} else {
$this->jsonEncodeOptions &= ~JSON_PRETTY_PRINT;
}
return $this;
}
/**
* Setting a base path will hide the base path from exception and stack trace file names to shorten them
* @return $this
*/
public function setBasePath(string $path = ''): self
{
if ($path !== '') {
$path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
$this->basePath = $path;
return $this;
}
/**
* Provided as extension point
*
* Because normalize is called with sub-values of context data etc, normalizeRecord can be
* extended when data needs to be appended on the record array but not to other normalized data.
*
* @return array<mixed[]|scalar|null>
*/
protected function normalizeRecord(LogRecord $record): array
{
/** @var array<mixed> $normalized */
$normalized = $this->normalize($record->toArray());
return $normalized;
}
/**
* @return null|scalar|array<mixed[]|scalar|null>
*/
protected function normalize(mixed $data, int $depth = 0): mixed
{
if ($depth > $this->maxNormalizeDepth) {
return 'Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization';
}
if (null === $data || \is_scalar($data)) {
if (\is_float($data)) {
if (is_infinite($data)) {
return ($data > 0 ? '' : '-') . 'INF';
}
if (is_nan($data)) {
return 'NaN';
}
}
return $data;
}
if (\is_array($data)) {
$normalized = [];
$count = 1;
foreach ($data as $key => $value) {
if ($count++ > $this->maxNormalizeItemCount) {
$normalized['...'] = 'Over ' . $this->maxNormalizeItemCount . ' items ('.\count($data).' total), aborting normalization';
break;
}
$normalized[$key] = $this->normalize($value, $depth + 1);
}
return $normalized;
}
if ($data instanceof \DateTimeInterface) {
return $this->formatDate($data);
}
if (\is_object($data)) {
if ($data instanceof Throwable) {
return $this->normalizeException($data, $depth);
}
if ($data instanceof \JsonSerializable) {
/** @var null|scalar|array<mixed[]|scalar|null> $value */
$value = $data->jsonSerialize();
} elseif (\get_class($data) === '__PHP_Incomplete_Class') {
$accessor = new \ArrayObject($data);
$value = (string) $accessor['__PHP_Incomplete_Class_Name'];
} elseif (method_exists($data, '__toString')) {
try {
/** @var string $value */
$value = $data->__toString();
} catch (\Throwable) {
// if the toString method is failing, use the default behavior
/** @var null|scalar|array<mixed[]|scalar|null> $value */
$value = json_decode($this->toJson($data, true), true);
}
} else {
// the rest is normalized by json encoding and decoding it
/** @var null|scalar|array<mixed[]|scalar|null> $value */
$value = json_decode($this->toJson($data, true), true);
}
return [Utils::getClass($data) => $value];
}
if (\is_resource($data)) {
return sprintf('[resource(%s)]', get_resource_type($data));
}
return '[unknown('.\gettype($data).')]';
}
/**
* @return mixed[]
*/
protected function normalizeException(Throwable $e, int $depth = 0)
{
if ($depth > $this->maxNormalizeDepth) {
return ['Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization'];
}
if ($e instanceof \JsonSerializable) {
return (array) $e->jsonSerialize();
}
$file = $e->getFile();
if ($this->basePath !== '') {
$file = preg_replace('{^'.preg_quote($this->basePath).'}', '', $file);
}
$data = [
'class' => Utils::getClass($e),
'message' => $e->getMessage(),
'code' => (int) $e->getCode(),
'file' => $file.':'.$e->getLine(),
];
if ($e instanceof \SoapFault) {
if (isset($e->faultcode)) {
$data['faultcode'] = $e->faultcode;
}
if (isset($e->faultactor)) {
$data['faultactor'] = $e->faultactor;
}
if (isset($e->detail)) {
if (\is_string($e->detail)) {
$data['detail'] = $e->detail;
} elseif (\is_object($e->detail) || \is_array($e->detail)) {
$data['detail'] = $this->toJson($e->detail, true);
}
}
}
$trace = $e->getTrace();
foreach ($trace as $frame) {
if (isset($frame['file'], $frame['line'])) {
$file = $frame['file'];
if ($this->basePath !== '') {
$file = preg_replace('{^'.preg_quote($this->basePath).'}', '', $file);
}
$data['trace'][] = $file.':'.$frame['line'];
}
}
if (($previous = $e->getPrevious()) instanceof \Throwable) {
$data['previous'] = $this->normalizeException($previous, $depth + 1);
}
return $data;
}
/**
* Return the JSON representation of a value
*
* @param mixed $data
* @throws \RuntimeException if encoding fails and errors are not ignored
* @return string if encoding fails and ignoreErrors is true 'null' is returned
*/
protected function toJson($data, bool $ignoreErrors = false): string
{
return Utils::jsonEncode($data, $this->jsonEncodeOptions, $ignoreErrors);
}
protected function formatDate(\DateTimeInterface $date): string
{
// in case the date format isn't custom then we defer to the custom DateTimeImmutable
// formatting logic, which will pick the right format based on whether useMicroseconds is on
if ($this->dateFormat === self::SIMPLE_DATE && $date instanceof DateTimeImmutable) {
return (string) $date;
}
return $date->format($this->dateFormat);
}
/**
* @return $this
*/
public function addJsonEncodeOption(int $option): self
{
$this->jsonEncodeOptions |= $option;
return $this;
}
/**
* @return $this
*/
public function removeJsonEncodeOption(int $option): self
{
$this->jsonEncodeOptions &= ~$option;
return $this;
}
}