ILIAS  release_5-3 Revision v5.3.23-19-g915713cf615
Monolog\Formatter\NormalizerFormatter Class Reference

Normalizes incoming records to remove objects/resources so it's easier to dump to various targets. More...

+ Inheritance diagram for Monolog\Formatter\NormalizerFormatter:
+ Collaboration diagram for Monolog\Formatter\NormalizerFormatter:

Public Member Functions

 __construct ($dateFormat=null)
 
 format (array $record)
 {Formats a log record.
Parameters
array$recordA record to format
Returns
mixed The formatted record
} More...
 
 formatBatch (array $records)
 {Formats a set of log records.
Parameters
array$recordsA set of records to format
Returns
mixed The formatted set of records
} More...
 
 detectAndCleanUtf8 (&$data)
 Detect invalid UTF-8 string characters and convert to valid UTF-8. More...
 
 format (array $record)
 Formats a log record. More...
 
 formatBatch (array $records)
 Formats a set of log records. More...
 

Data Fields

const SIMPLE_DATE = "Y-m-d H:i:s"
 

Protected Member Functions

 normalize ($data)
 
 normalizeException ($e)
 
 toJson ($data, $ignoreErrors=false)
 Return the JSON representation of a value. More...
 

Protected Attributes

 $dateFormat
 

Private Member Functions

 jsonEncode ($data)
 
 handleJsonError ($code, $data)
 Handle a json_encode failure. More...
 
 throwEncodeError ($code, $data)
 Throws an exception according to a given code with a customized message. More...
 

Detailed Description

Normalizes incoming records to remove objects/resources so it's easier to dump to various targets.

Author
Jordi Boggiano j.bog.nosp@m.gian.nosp@m.o@sel.nosp@m.d.be

Definition at line 21 of file NormalizerFormatter.php.

Constructor & Destructor Documentation

◆ __construct()

Monolog\Formatter\NormalizerFormatter::__construct (   $dateFormat = null)
Parameters
string$dateFormatThe format of the timestamp: one supported by DateTime::format

Reimplemented in Monolog\Formatter\HtmlFormatter.

Definition at line 30 of file NormalizerFormatter.php.

31 {
32 $this->dateFormat = $dateFormat ?: static::SIMPLE_DATE;
33 if (!function_exists('json_encode')) {
34 throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s NormalizerFormatter');
35 }
36 }

References Monolog\Formatter\NormalizerFormatter\$dateFormat.

Member Function Documentation

◆ detectAndCleanUtf8()

Monolog\Formatter\NormalizerFormatter::detectAndCleanUtf8 ( $data)

Detect invalid UTF-8 string characters and convert to valid UTF-8.

Valid UTF-8 input will be left unmodified, but strings containing invalid UTF-8 codepoints will be reencoded as UTF-8 with an assumed original encoding of ISO-8859-15. This conversion may result in incorrect output if the actual encoding was not ISO-8859-15, but it will be clean UTF-8 output and will not rely on expensive and fragile detection algorithms.

Function converts the input in place in the passed variable so that it can be used as a callback for array_walk_recursive.

Parameters
mixed&$dataInput to check and convert if needed

Definition at line 282 of file NormalizerFormatter.php.

283 {
284 if (is_string($data) && !preg_match('//u', $data)) {
285 $data = preg_replace_callback(
286 '/[\x80-\xFF]+/',
287 function ($m) { return utf8_encode($m[0]); },
288 $data
289 );
290 $data = str_replace(
291 array('¤', '¦', '¨', '´', '¸', '¼', '½', '¾'),
292 array('€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'),
293 $data
294 );
295 }
296 }

References $data, and $m.

Referenced by Monolog\Formatter\NormalizerFormatter\handleJsonError().

+ Here is the caller graph for this function:

◆ format()

Monolog\Formatter\NormalizerFormatter::format ( array  $record)

◆ formatBatch()

Monolog\Formatter\NormalizerFormatter::formatBatch ( array  $records)

{Formats a set of log records.

Parameters
array$recordsA set of records to format
Returns
mixed The formatted set of records
}

Implements Monolog\Formatter\FormatterInterface.

Reimplemented in Monolog\Formatter\HtmlFormatter, Monolog\Formatter\JsonFormatter, Monolog\Formatter\LineFormatter, and Monolog\Formatter\WildfireFormatter.

Definition at line 49 of file NormalizerFormatter.php.

50 {
51 foreach ($records as $key => $record) {
52 $records[$key] = $this->format($record);
53 }
54
55 return $records;
56 }
format(array $record)
{Formats a log record.mixed The formatted record}
$key
Definition: croninfo.php:18
$records
Definition: simple_test.php:22

References $key, $records, and Monolog\Formatter\NormalizerFormatter\format().

+ Here is the call graph for this function:

◆ handleJsonError()

Monolog\Formatter\NormalizerFormatter::handleJsonError (   $code,
  $data 
)
private

Handle a json_encode failure.

If the failure is due to invalid string encoding, try to clean the input and encode again. If the second encoding attempt fails, the inital error is not encoding related or the input can't be cleaned then raise a descriptive exception.

Parameters
int$codereturn code of json_last_error function
mixed$datadata that was meant to be encoded
Exceptions

RuntimeException if failure can't be corrected

Returns
string JSON encoded data after error correction

Definition at line 214 of file NormalizerFormatter.php.

215 {
216 if ($code !== JSON_ERROR_UTF8) {
218 }
219
220 if (is_string($data)) {
222 } elseif (is_array($data)) {
223 array_walk_recursive($data, array($this, 'detectAndCleanUtf8'));
224 } else {
226 }
227
228 $json = $this->jsonEncode($data);
229
230 if ($json === false) {
231 $this->throwEncodeError(json_last_error(), $data);
232 }
233
234 return $json;
235 }
detectAndCleanUtf8(&$data)
Detect invalid UTF-8 string characters and convert to valid UTF-8.
throwEncodeError($code, $data)
Throws an exception according to a given code with a customized message.
$code
Definition: example_050.php:99

References $code, $data, Monolog\Formatter\NormalizerFormatter\detectAndCleanUtf8(), Monolog\Formatter\NormalizerFormatter\jsonEncode(), and Monolog\Formatter\NormalizerFormatter\throwEncodeError().

Referenced by Monolog\Formatter\NormalizerFormatter\toJson().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ jsonEncode()

Monolog\Formatter\NormalizerFormatter::jsonEncode (   $data)
private
Parameters
mixed$data
Returns
string JSON encoded data or null on failure

Definition at line 192 of file NormalizerFormatter.php.

193 {
194 if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
195 return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
196 }
197
198 return json_encode($data);
199 }

References $data.

Referenced by Monolog\Formatter\NormalizerFormatter\handleJsonError(), and Monolog\Formatter\NormalizerFormatter\toJson().

+ Here is the caller graph for this function:

◆ normalize()

Monolog\Formatter\NormalizerFormatter::normalize (   $data)
protected

Reimplemented in Monolog\Formatter\JsonFormatter, and Monolog\Formatter\WildfireFormatter.

Definition at line 58 of file NormalizerFormatter.php.

59 {
60 if (null === $data || is_scalar($data)) {
61 if (is_float($data)) {
62 if (is_infinite($data)) {
63 return ($data > 0 ? '' : '-') . 'INF';
64 }
65 if (is_nan($data)) {
66 return 'NaN';
67 }
68 }
69
70 return $data;
71 }
72
73 if (is_array($data) || $data instanceof \Traversable) {
74 $normalized = array();
75
76 $count = 1;
77 foreach ($data as $key => $value) {
78 if ($count++ >= 1000) {
79 $normalized['...'] = 'Over 1000 items, aborting normalization';
80 break;
81 }
82 $normalized[$key] = $this->normalize($value);
83 }
84
85 return $normalized;
86 }
87
88 if ($data instanceof \DateTime) {
89 return $data->format($this->dateFormat);
90 }
91
92 if (is_object($data)) {
93 // TODO 2.0 only check for Throwable
94 if ($data instanceof Exception || (PHP_VERSION_ID > 70000 && $data instanceof \Throwable)) {
95 return $this->normalizeException($data);
96 }
97
98 // non-serializable objects that implement __toString stringified
99 if (method_exists($data, '__toString') && !$data instanceof \JsonSerializable) {
100 $value = $data->__toString();
101 } else {
102 // the rest is json-serialized in some way
103 $value = $this->toJson($data, true);
104 }
105
106 return sprintf("[object] (%s: %s)", get_class($data), $value);
107 }
108
109 if (is_resource($data)) {
110 return sprintf('[resource] (%s)', get_resource_type($data));
111 }
112
113 return '[unknown('.gettype($data).')]';
114 }
sprintf('%.4f', $callTime)
toJson($data, $ignoreErrors=false)
Return the JSON representation of a value.

References $data, $key, Monolog\Formatter\NormalizerFormatter\normalize(), Monolog\Formatter\NormalizerFormatter\normalizeException(), sprintf, and Monolog\Formatter\NormalizerFormatter\toJson().

Referenced by Monolog\Formatter\HtmlFormatter\convertToString(), Monolog\Formatter\NormalizerFormatter\format(), Monolog\Formatter\NormalizerFormatter\normalize(), Monolog\Formatter\NormalizerFormatter\normalizeException(), and Monolog\Formatter\ScalarFormatter\normalizeValue().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ normalizeException()

Monolog\Formatter\NormalizerFormatter::normalizeException (   $e)
protected

Reimplemented in Monolog\Formatter\JsonFormatter, and Monolog\Formatter\LineFormatter.

Definition at line 116 of file NormalizerFormatter.php.

117 {
118 // TODO 2.0 only check for Throwable
119 if (!$e instanceof Exception && !$e instanceof \Throwable) {
120 throw new \InvalidArgumentException('Exception/Throwable expected, got '.gettype($e).' / '.get_class($e));
121 }
122
123 $data = array(
124 'class' => get_class($e),
125 'message' => $e->getMessage(),
126 'code' => $e->getCode(),
127 'file' => $e->getFile().':'.$e->getLine(),
128 );
129
130 if ($e instanceof \SoapFault) {
131 if (isset($e->faultcode)) {
132 $data['faultcode'] = $e->faultcode;
133 }
134
135 if (isset($e->faultactor)) {
136 $data['faultactor'] = $e->faultactor;
137 }
138
139 if (isset($e->detail)) {
140 $data['detail'] = $e->detail;
141 }
142 }
143
144 $trace = $e->getTrace();
145 foreach ($trace as $frame) {
146 if (isset($frame['file'])) {
147 $data['trace'][] = $frame['file'].':'.$frame['line'];
148 } elseif (isset($frame['function']) && $frame['function'] === '{closure}') {
149 // We should again normalize the frames, because it might contain invalid items
150 $data['trace'][] = $frame['function'];
151 } else {
152 // We should again normalize the frames, because it might contain invalid items
153 $data['trace'][] = $this->toJson($this->normalize($frame), true);
154 }
155 }
156
157 if ($previous = $e->getPrevious()) {
158 $data['previous'] = $this->normalizeException($previous);
159 }
160
161 return $data;
162 }

References $data, Monolog\Formatter\NormalizerFormatter\normalize(), Monolog\Formatter\NormalizerFormatter\normalizeException(), and Monolog\Formatter\NormalizerFormatter\toJson().

Referenced by Monolog\Formatter\NormalizerFormatter\normalize(), and Monolog\Formatter\NormalizerFormatter\normalizeException().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ throwEncodeError()

Monolog\Formatter\NormalizerFormatter::throwEncodeError (   $code,
  $data 
)
private

Throws an exception according to a given code with a customized message.

Parameters
int$codereturn code of json_last_error function
mixed$datadata that was meant to be encoded
Exceptions

RuntimeException

Definition at line 244 of file NormalizerFormatter.php.

245 {
246 switch ($code) {
247 case JSON_ERROR_DEPTH:
248 $msg = 'Maximum stack depth exceeded';
249 break;
250 case JSON_ERROR_STATE_MISMATCH:
251 $msg = 'Underflow or the modes mismatch';
252 break;
253 case JSON_ERROR_CTRL_CHAR:
254 $msg = 'Unexpected control character found';
255 break;
256 case JSON_ERROR_UTF8:
257 $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
258 break;
259 default:
260 $msg = 'Unknown error';
261 }
262
263 throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true));
264 }

References $code, and $data.

Referenced by Monolog\Formatter\NormalizerFormatter\handleJsonError().

+ Here is the caller graph for this function:

◆ toJson()

Monolog\Formatter\NormalizerFormatter::toJson (   $data,
  $ignoreErrors = false 
)
protected

Return the JSON representation of a value.

Parameters
mixed$data
bool$ignoreErrors
Exceptions

RuntimeException if encoding fails and errors are not ignored

Returns
string

Definition at line 172 of file NormalizerFormatter.php.

173 {
174 // suppress json_encode errors since it's twitchy with some inputs
175 if ($ignoreErrors) {
176 return @$this->jsonEncode($data);
177 }
178
179 $json = $this->jsonEncode($data);
180
181 if ($json === false) {
182 $json = $this->handleJsonError(json_last_error(), $data);
183 }
184
185 return $json;
186 }
handleJsonError($code, $data)
Handle a json_encode failure.

References $data, Monolog\Formatter\NormalizerFormatter\handleJsonError(), and Monolog\Formatter\NormalizerFormatter\jsonEncode().

Referenced by Monolog\Formatter\LineFormatter\convertToString(), Monolog\Formatter\GelfMessageFormatter\format(), Monolog\Formatter\JsonFormatter\format(), Monolog\Formatter\LogstashFormatter\format(), Monolog\Formatter\WildfireFormatter\format(), Monolog\Formatter\JsonFormatter\formatBatchJson(), Monolog\Formatter\NormalizerFormatter\normalize(), Monolog\Formatter\NormalizerFormatter\normalizeException(), and Monolog\Formatter\ScalarFormatter\normalizeValue().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

Field Documentation

◆ $dateFormat

Monolog\Formatter\NormalizerFormatter::$dateFormat
protected

◆ SIMPLE_DATE

const Monolog\Formatter\NormalizerFormatter::SIMPLE_DATE = "Y-m-d H:i:s"

Definition at line 23 of file NormalizerFormatter.php.


The documentation for this class was generated from the following file: