Drupal syslog odd behaviour with json

306 Views Asked by At

I'm having some trouble understanding an issue I'm facing. I'm logging some message on a file with Drupal syslog, and the result on the file isn't the same as if I var_dump the message.

Here is an example :

$logMsg = 'LOGGING TEST : {"test": "test", "test1": {"test2": "test2", "test3":"test3"}}';

print_r($logMsg);

\Drupal::logger('TestLog')
   ->log(0,$logMsg);

The result of the print_r is fine : LOGGING TEST : {"test": "test", "test1": {"test2": "test2", "test3":"test3"}}

However the result in the file is not fine : LOGGING TEST : @"test": "test", "test1": {"test2": "test2", "test3":"test3"}

The first curly bracket is replaced by an @, and the last one is removed.

After some hours of testing I can't find why it's doing that, does someone has any idea ?

The version of Drupal is 8.9.5 and PHP 7.3.22.

Thanks

1

There are 1 best solutions below

0
On

This has to do with the way that the Drupal logger parses the message string.

\Drupal::logger('TestLog') returns a LoggerInterface, which is documented at https://api.drupal.org/api/drupal/vendor%21psr%21log%21Psr%21Log%21LoggerInterface.php/interface/LoggerInterface/9.1.x . The log() method is documented at https://api.drupal.org/api/drupal/vendor%21psr%21log%21Psr%21Log%21LoggerInterface.php/function/LoggerInterface%3A%3Alog/9.1.x . But the answer is actually in the docs of LoggerInterface rather than the docs of log():

The message MAY contain placeholders in the form: {foo} where foo will be replaced by the context data in key "foo".

So instead of embedding your JSON string in $message, do this:

\Drupal::logger('TestLog')->log(
  \Psr\Log\LogLevel::ERROR,
  "LOGGING TEST : {json_data}",
  [
    'json_data' => '{"test": "test", "test1": {"test2": "test2", "test3":"test3"}}',
  ]
);