我无法理解我面临的问题。我正在使用 Drupal syslog 在文件上记录一些消息,文件上的结果与我 var_dump 消息不同。
这是一个例子:
$logMsg = 'LOGGING TEST : {"test": "test", "test1": {"test2": "test2", "test3":"test3"}}';
print_r($logMsg);
\Drupal::logger('TestLog')
->log(0,$logMsg);
print_r
的结果很好:LOGGING TEST : {"test": "test", "test1": {"test2": "test2", "test3":"test3"}}
但是文件中的结果并不好:
LOGGING TEST : @"test": "test", "test1": {"test2": "test2", "test3":"test3"}
第一个大括号被@替换,最后一个被删除。
经过几个小时的测试,我找不到为什么这样做,有人知道吗?
Drupal 版本为 8.9.5,PHP 7.3.22。
谢谢
这与 Drupal 记录器解析消息字符串的方式有关。
\Drupal::logger('TestLog')
返回一个LoggerInterface
,记录在https://api.drupal.org/api/drupal/vendor%21psr%21log%21Psr%21Log%21LoggerInterface.php/interface/LoggerInterface/9.1.x 。 log()
方法记录在 https://api.drupal.org/api/drupal/vendor%21psr%21log%21Psr%21Log%21LoggerInterface.php/function/LoggerInterface%3A%3Alog/9.1.x 。但答案实际上在 LoggerInterface
的文档中,而不是 log()
的文档中:
消息可以包含以下形式的占位符:{foo},其中 foo 将被键“foo”中的上下文数据替换。
因此,不要将 JSON 字符串嵌入到
$message
中,而是这样做:
\Drupal::logger('TestLog')->log(
\Psr\Log\LogLevel::ERROR,
"LOGGING TEST : {json_data}",
[
'json_data' => '{"test": "test", "test1": {"test2": "test2", "test3":"test3"}}',
]
);
上面它正在保存消息,例如:
LOGGING TEST : {\"test\": \"test\", \"test1\" : {\"test2\": \"test2\", \"test3\":\"test3\"}}