Skip to main content

In Drupal, the logging system is based on the PSR-3 logging standard, which Drupal integrates through the \Psr\Log\LoggerInterface. When you want to log messages, you typically use placeholders in your message string, which are replaced with context array values. However, if you're dealing with a situation where you have a complex message or an object implementing the \Drupal\Core\Logger\RfcLogLevel\MessageInterface, and you want to log the entire object or message as it is, you might need to handle it differently since the logger interface expects a string message and an array of context data.

The \Drupal\Core\Logger\RfcLogLevel\MessageInterface is not directly related to logging messages but rather to defining RFC log levels. For logging complex messages or objects, you should convert the message or object to a string format, if possible, or serialize it to a string representation that can be logged.

Your approach to logging an entire object or a complex message, by serialising or converting the object to a string

// Get the logger service.
$logger = \Drupal::logger('your_module_name');

// Check if the $message can be directly converted to a string or needs serialization.
if (is_object($message) && method_exists($message, '__toString')) {
   // If your object can be converted to a string, use __toString().
   $log_message = $message->__toString();
} else {
   // Otherwise, serialise the object to a string.
   // Note: Serialisation might not be suitable for all objects, especially if they contain resources or sensitive information.
   $log_message = serialize($message);
}

// Log the message.
// You might want to use a specific log level like debug, info, notice, warning, etc.
$logger->notice($log_message);

Please ensure that serialisation is suitable for your use case, as it might not be the best approach for all types of objects, especially for those containing resources or sensitive data. Also, note that using serialisation can make the log harder to read, so for debugging purposes, you might consider logging specific properties of the object instead.

Remember to replace 'your_module_name' with the actual name of your module. This code snippet assumes that you're working within a context where \Drupal is available; if you're working in an object-oriented context (like a service or a controller), it's better to inject the logger service rather than calling \Drupal::logger().

Related articles