How to log error messages in Drupal 9

Messages can be logged in Drupal using Logger service,

$message = 'custom message or a variable value that needs to be logged';

// Logs a notice

\Drupal::logger('custom_module_name')->notice($message);

// Logs an error

\Drupal::logger('custom_module_name')->error($message);

// Logs an array or object

\Drupal::logger('module_name')->notice('<pre>'.print_r($array, TRUE).'</pre>');

 

Category