Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ad7d0d4

Browse files
committed
update: 消息标准化处理
1 parent 9007974 commit ad7d0d4

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

think/SocketV2.php

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -197,9 +197,7 @@ public function save(array $log = []): bool
197197
'css' => $this->css[$type] ?? '',
198198
];
199199
foreach ($messages as $msg) {
200-
if (!is_string($msg)) {
201-
$msg = var_export($msg, true);
202-
}
200+
$msg = $this->normalizeMessage($msg);
203201
$msg = $format ? $this->formatMessage($format, $type, $msg) : "[{$type}] {$msg}";
204202
$trace[] = [
205203
'type' => 'log',
@@ -222,9 +220,7 @@ public function save(array $log = []): bool
222220
foreach ($this->logReader($log, false) as $item) {
223221
[$type, $messages] = $item;
224222
$ctx = $item[2] ?? null;
225-
if (!is_string($messages)) {
226-
$messages = var_export($messages, true);
227-
}
223+
$messages = $this->normalizeMessage($messages);
228224
$css = $this->css2[$type] ?? '';
229225
if (in_array($css, self::LogLevelSet, true)) {
230226
$css = $this->css2[$css] ?? '';
@@ -288,6 +284,23 @@ public function save(array $log = []): bool
288284
return true;
289285
}
290286

287+
protected function normalizeMessage($message): string
288+
{
289+
if (!\is_string($message)) {
290+
if ((is_object($message) && method_exists($message, '__toString')) || $message instanceof \Stringable) {
291+
$message = (string) $message;
292+
} else {
293+
try {
294+
$message = var_export($message, true);
295+
} catch (\Throwable $e) {
296+
$message = '[Unable to cast to string]';
297+
}
298+
}
299+
}
300+
301+
return $message;
302+
}
303+
291304
protected function formatMessage(string $format, string $level, string $messages, ?array $context = null): string
292305
{
293306
if (!str_contains($format, '{')) {

0 commit comments

Comments
 (0)