13.11.2025 | Mathias Grab

How to add a Drupal error message and log entry

error_handling.php
<?php

$error_message = t('There is an error with this.');

\Drupal::messenger()->addError($error_message));
\Drupal::logger('my_module')->log('error', $error_message);

Issue:

You would like to create a custom error message shown on the page. Also, if the error occurs, it should be properly logged in the recent log messages backend area (`/admin/reports/dblog`) of your site.

Solution:

Use the Drupal logger and messenger service to create the errors.