From b84b827d42512f5add026b6c930d9087c79a4b7c Mon Sep 17 00:00:00 2001
From: Alex Pott <alex.a.pott@googlemail.com>
Date: Tue, 1 May 2018 10:15:07 +0100
Subject: [PATCH] Issue #2935256 by Jo Fitzgerald, voleger, kim.pepper,
 ibustos, Yogesh Pawar, catch, jibran: Remove all usages of drupal_get_message
 and drupal_set_message in modules

---
 core/lib/Drupal/Core/Form/ConfigFormBase.php  |   4 +-
 .../lib/Drupal/Core/Form/FormErrorHandler.php |  15 +--
 core/modules/action/src/ActionFormBase.php    |   2 +-
 .../src/Plugin/Action/MessageAction.php       |  17 ++-
 core/modules/aggregator/src/FeedForm.php      |   4 +-
 .../aggregator/src/Form/OpmlFeedAdd.php       |  10 +-
 .../aggregator/fetcher/DefaultFetcher.php     |  18 +++-
 .../aggregator/parser/DefaultParser.php       |   5 +-
 .../aggregator/processor/DefaultProcessor.php |  21 +++-
 .../AggregatorPluginSettingsBaseTest.php      |  14 ++-
 core/modules/ban/src/Form/BanAdmin.php        |   2 +-
 core/modules/ban/src/Form/BanDelete.php       |   2 +-
 core/modules/big_pipe/src/Render/BigPipe.php  |   4 +-
 .../src/BigPipeTestController.php             |   2 +-
 core/modules/block/block.module               |   6 +-
 core/modules/block/src/BlockForm.php          |   2 +-
 core/modules/block/src/BlockListBuilder.php   |  16 ++-
 .../block/src/Controller/BlockController.php  |   2 +-
 .../Controller/TestMultipleFormController.php |   5 +-
 .../src/Form/FavoriteAnimalTestForm.php       |   2 +-
 .../modules/block_test/src/Form/TestForm.php  |   2 +-
 .../Plugin/Block/TestContextAwareBlock.php    |   5 +-
 .../tests/src/Kernel/BlockRebuildTest.php     |   9 +-
 .../block_content/src/BlockContentForm.php    |   6 +-
 .../src/BlockContentTypeForm.php              |   4 +-
 .../book/src/Controller/BookController.php    |   2 +-
 .../book/src/Form/BookAdminEditForm.php       |   2 +-
 .../modules/book/src/Form/BookOutlineForm.php |   8 +-
 core/modules/book/src/Form/BookRemoveForm.php |   2 +-
 .../tests/modules/book_test/book_test.module  |   2 +-
 core/modules/color/color.module               |   2 +-
 core/modules/comment/src/CommentForm.php      |   6 +-
 core/modules/comment/src/CommentTypeForm.php  |   4 +-
 .../src/Controller/CommentController.php      |   2 +-
 .../comment/src/Form/CommentAdminOverview.php |   2 +-
 .../views/field/CommentBulkFormTest.php       |   4 +-
 .../config/src/Form/ConfigImportForm.php      |   6 +-
 .../src/Form/ConfigSingleImportForm.php       |   6 +-
 core/modules/config/src/Form/ConfigSync.php   |  18 ++--
 .../tests/config_test/src/ConfigTestForm.php  |   4 +-
 .../ConfigTranslationController.php           |   4 +-
 .../src/Form/ConfigTranslationAddForm.php     |   2 +-
 .../src/Form/ConfigTranslationDeleteForm.php  |   2 +-
 .../src/Form/ConfigTranslationEditForm.php    |   2 +-
 .../contact/src/ContactFormEditForm.php       |   4 +-
 .../src/Controller/ContactController.php      |   4 +-
 core/modules/contact/src/MessageForm.php      |   2 +-
 .../src/Form/EntityModerationForm.php         |   2 +-
 .../Plugin/Action/ModerationOptOutPublish.php |  21 +++-
 .../Action/ModerationOptOutUnpublish.php      |  21 +++-
 .../content_translation.install               |   4 +-
 .../src/ContentTranslationHandler.php         |   4 +-
 .../src/Form/DblogClearLogConfirmForm.php     |   2 +-
 core/modules/field/field.module               |   4 +-
 .../modules/field_test/field_test.module      |   5 +-
 .../src/Form/NestedEntityTestForm.php         |   4 +-
 .../src/Form/EntityDisplayFormBase.php        |   6 +-
 .../src/Form/EntityDisplayModeFormBase.php    |   2 +-
 .../src/Form/FieldConfigDeleteForm.php        |   4 +-
 .../field_ui/src/Form/FieldConfigEditForm.php |   2 +-
 .../field_ui/src/Form/FieldStorageAddForm.php |   6 +-
 .../src/Form/FieldStorageConfigEditForm.php   |   4 +-
 core/modules/file/file.module                 |  43 ++++----
 .../Plugin/Field/FieldWidget/FileWidget.php   |   2 +-
 .../src/Form/FileModuleTestForm.php           |   2 +-
 .../tests/file_test/src/Form/FileTestForm.php |  10 +-
 .../filter/src/FilterFormatAddForm.php        |   2 +-
 .../filter/src/FilterFormatEditForm.php       |   2 +-
 .../filter/src/FilterFormatFormBase.php       |   2 +-
 .../filter/src/FilterFormatListBuilder.php    |  18 +++-
 .../filter/src/Form/FilterDisableForm.php     |   2 +-
 .../tests/filter_test/filter_test.module      |   6 +-
 core/modules/forum/src/Form/DeleteForm.php    |   2 +-
 core/modules/forum/src/Form/ForumForm.php     |   4 +-
 .../help/src/Controller/HelpController.php    |   2 +-
 .../image/src/Form/ImageEffectDeleteForm.php  |   2 +-
 .../image/src/Form/ImageEffectFormBase.php    |   2 +-
 .../image/src/Form/ImageStyleAddForm.php      |   2 +-
 .../image/src/Form/ImageStyleEditForm.php     |   4 +-
 .../image/src/Form/ImageStyleFlushForm.php    |   2 +-
 .../src/FormErrorHandler.php                  |  17 ++-
 .../src/InlineFormErrorsServiceProvider.php   |   7 +-
 .../tests/src/Unit/FormErrorHandlerTest.php   | 101 +++++++++++-------
 .../src/Form/ContentLanguageSettingsForm.php  |   2 +-
 .../language/src/Form/LanguageAddForm.php     |   4 +-
 .../src/Form/NegotiationBrowserDeleteForm.php |   2 +-
 .../src/Form/NegotiationConfigureForm.php     |   2 +-
 .../language/src/LanguageListBuilder.php      |  18 +++-
 .../tests/language_test/language_test.module  |   2 +-
 core/modules/locale/locale.batch.inc          |   8 +-
 core/modules/locale/locale.bulk.inc           |  10 +-
 core/modules/locale/src/Form/ExportForm.php   |   2 +-
 core/modules/locale/src/Form/ImportForm.php   |   2 +-
 .../locale/src/Form/TranslateEditForm.php     |   2 +-
 .../Form/MediaDeleteMultipleConfirmForm.php   |   2 +-
 core/modules/media/src/MediaForm.php          |   4 +-
 core/modules/media/src/MediaTypeForm.php      |   4 +-
 .../src/Form/MenuLinkContentForm.php          |   4 +-
 .../menu_ui/src/Form/MenuLinkEditForm.php     |   2 +-
 .../menu_ui/src/Form/MenuLinkResetForm.php    |   2 +-
 core/modules/menu_ui/src/MenuForm.php         |   4 +-
 .../migrate_drupal_ui.install                 |   2 +-
 .../src/Batch/MigrateUpgradeImportBatch.php   |  10 +-
 core/modules/node/node.admin.inc              |   8 +-
 core/modules/node/node.module                 |   8 +-
 core/modules/node/src/Entity/NodeType.php     |   2 +-
 .../node/src/Form/NodeRevisionDeleteForm.php  |   7 +-
 .../node/src/Form/NodeRevisionRevertForm.php  |   7 +-
 core/modules/node/src/NodeForm.php            |   6 +-
 core/modules/node/src/NodeTypeForm.php        |   4 +-
 .../node/src/Plugin/Search/NodeSearch.php     |  20 +++-
 .../tests/modules/node_test/node_test.module  |   4 +-
 .../Plugin/views/field/NodeBulkFormTest.php   |   4 +-
 core/modules/path/src/Form/PathFormBase.php   |   2 +-
 .../src/ResponsiveImageStyleForm.php          |   2 +-
 .../src/Controller/SearchController.php       |   8 +-
 .../search/src/Form/ReindexConfirm.php        |   2 +-
 .../search/src/Form/SearchPageAddForm.php     |   2 +-
 .../search/src/Form/SearchPageEditForm.php    |   2 +-
 .../search/src/SearchPageListBuilder.php      |  20 +++-
 .../src/Form/SearchEmbeddedForm.php           |   2 +-
 .../search_langcode_test.module               |   4 +-
 .../src/Controller/ShortcutController.php     |   4 +-
 .../src/Controller/ShortcutSetController.php  |   4 +-
 .../shortcut/src/Form/SetCustomize.php        |   2 +-
 .../shortcut/src/Form/SwitchShortcutSet.php   |   6 +-
 core/modules/shortcut/src/ShortcutForm.php    |   2 +-
 core/modules/shortcut/src/ShortcutSetForm.php |   4 +-
 core/modules/simpletest/simpletest.module     |  18 ++--
 .../src/Form/SimpletestResultsForm.php        |   2 +-
 core/modules/simpletest/src/TestBase.php      |   2 +-
 .../src/Controller/DbUpdateController.php     |   4 +-
 .../src/Controller/SystemController.php       |   2 +-
 .../system/src/Controller/ThemeController.php |  30 +++---
 core/modules/system/src/CronController.php    |   4 +-
 core/modules/system/src/Form/CronForm.php     |   6 +-
 .../system/src/Form/DateFormatFormBase.php    |   6 +-
 .../src/Form/ModulesListConfirmForm.php       |  14 ++-
 .../ModulesListExperimentalConfirmForm.php    |   2 +-
 .../system/src/Form/ModulesListForm.php       |  14 ++-
 .../src/Form/ModulesUninstallConfirmForm.php  |   4 +-
 .../system/src/Form/PerformanceForm.php       |   2 +-
 .../PrepareModulesEntityUninstallForm.php     |   2 +-
 .../src/Plugin/Block/SystemMessagesBlock.php  |   2 +-
 .../Tests/Form/ElementsTableSelectTest.php    |   2 +-
 .../Tests/Theme/ThemeSuggestionsAlterTest.php |   2 +-
 core/modules/system/system.module             |  12 ++-
 .../ajax_forms_test/ajax_forms_test.module    |   8 +-
 .../src/Form/AjaxFormsTestValidationForm.php  |   2 +-
 .../src/Plugin/Block/AjaxFormBlock.php        |  18 +++-
 .../batch_test/batch_test.callbacks.inc       |   2 +-
 .../condition_test/src/FormController.php     |   4 +-
 .../entity_test/src/EntityTestForm.php        |   4 +-
 .../tests/modules/form_test/form_test.module  |  10 +-
 .../tests/modules/form_test/src/Callbacks.php |   2 +-
 .../form_test/src/ConfirmFormTestForm.php     |   2 +-
 .../src/Form/FormTestClickedButtonForm.php    |   6 +-
 .../form_test/src/Form/FormTestGetForm.php    |   2 +-
 .../FormTestLimitValidationErrorsForm.php     |   2 +-
 .../FormTestRebuildPreserveValuesForm.php     |   2 +-
 .../src/Form/FormTestStatePersistForm.php     |   2 +-
 .../src/Form/FormTestStorageForm.php          |   8 +-
 .../FormTestTableSelectMultipleFalseForm.php  |   2 +-
 .../FormTestTableSelectMultipleTrueForm.php   |   2 +-
 .../src/Form/FormTestValidateForm.php         |   2 +-
 .../src/Form/FormTestValidateNoToken.php      |   2 +-
 .../src/Form/FormTestValidateRequiredForm.php |   2 +-
 .../FormTestValidateRequiredNoTitleForm.php   |   2 +-
 .../Form/FormTestVerticalTabsAccessForm.php   |   2 +-
 .../form_test/src/FormTestArgumentsObject.php |   4 +-
 .../src/FormTestControllerObject.php          |   6 +-
 .../modules/form_test/src/FormTestObject.php  |   4 +-
 .../form_test/src/FormTestServiceObject.php   |   4 +-
 .../src/Controller/PagerTestController.php    |   2 +-
 ...RenderPlaceholderMessageTestController.php |   2 +-
 .../service_provider_test/src/TestClass.php   |   2 +-
 .../src/Controller/SessionTestController.php  |   2 +-
 .../session_test/src/Form/SessionTestForm.php |   2 +-
 .../src/Controller/SystemTestController.php   |  28 ++---
 .../modules/system_test/system_test.module    |   6 +-
 .../theme_suggestions_test.module             |   4 +-
 .../modules/theme_test/theme_test.module      |   4 +-
 .../update_script_test.module                 |   2 +-
 .../tests/src/Functional/Form/FormTest.php    |   2 +-
 .../Module/InstallUninstallTest.php           |   3 +-
 .../ServiceProviderWebTest.php                |   7 +-
 .../tests/src/Kernel/Render/ClassyTest.php    |   4 +-
 .../tests/themes/test_theme/test_theme.theme  |   4 +-
 .../taxonomy/src/Form/OverviewTerms.php       |   2 +-
 .../taxonomy/src/Form/VocabularyResetForm.php |   2 +-
 core/modules/taxonomy/src/TermForm.php        |   4 +-
 core/modules/taxonomy/src/VocabularyForm.php  |   4 +-
 .../taxonomy/src/VocabularyListBuilder.php    |  22 +++-
 .../update/src/Form/UpdateManagerInstall.php  |  20 ++--
 .../tests/src/Functional/UpdateCoreTest.php   |   5 +-
 core/modules/update/update.manager.inc        |   6 +-
 core/modules/update/update.module             |  15 +--
 .../user/src/Controller/UserController.php    |  19 ++--
 core/modules/user/src/Form/UserCancelForm.php |   2 +-
 .../src/Form/UserMultipleCancelConfirm.php    |   3 +-
 .../user/src/Form/UserPasswordForm.php        |   2 +-
 .../user/src/Form/UserPermissionsForm.php     |   2 +-
 core/modules/user/src/ProfileForm.php         |   2 +-
 core/modules/user/src/RegisterForm.php        |  12 +--
 core/modules/user/src/RoleForm.php            |   4 +-
 core/modules/user/src/RoleListBuilder.php     |  41 ++++++-
 .../Plugin/views/field/UserBulkFormTest.php   |   4 +-
 core/modules/user/user.api.php                |   9 +-
 core/modules/user/user.module                 |   6 +-
 core/modules/views/src/Analyzer.php           |   3 +-
 .../views/src/DisplayPluginCollection.php     |   2 +-
 .../ViewsSelection.php                        |   2 +-
 .../views/src/Plugin/views/area/View.php      |   2 +-
 .../views/src/Plugin/views/field/BulkForm.php |  33 +++---
 .../views/src/Plugin/views/query/Sql.php      |  21 +++-
 .../views/field/FieldFormButtonTest.php       |   4 +-
 .../views_test_data/views_test_data.module    |   2 +-
 .../src/Kernel/Handler/AreaMessagesTest.php   |   2 +-
 .../tests/src/Unit/Plugin/query/SqlTest.php   |  28 +++--
 core/modules/views/views.api.php              |   4 +-
 .../src/Form/AdvancedSettingsForm.php         |   2 +-
 .../views_ui/src/Form/BreakLockForm.php       |   2 +-
 core/modules/views_ui/src/ViewAddForm.php     |   4 +-
 core/modules/views_ui/src/ViewEditForm.php    |   2 +-
 core/modules/views_ui/src/ViewUI.php          |   4 +-
 .../workflows/src/Form/WorkflowAddForm.php    |   4 +-
 .../workflows/src/Form/WorkflowDeleteForm.php |   2 +-
 .../workflows/src/Form/WorkflowEditForm.php   |   7 +-
 .../src/Form/WorkflowStateAddForm.php         |   2 +-
 .../src/Form/WorkflowStateDeleteForm.php      |   2 +-
 .../src/Form/WorkflowStateEditForm.php        |   2 +-
 .../src/Form/WorkflowTransitionAddForm.php    |   2 +-
 .../src/Form/WorkflowTransitionDeleteForm.php |   2 +-
 .../src/Form/WorkflowTransitionEditForm.php   |   2 +-
 .../Tests/Core/Form/FormErrorHandlerTest.php  |  68 ++++++++----
 235 files changed, 931 insertions(+), 593 deletions(-)

diff --git a/core/lib/Drupal/Core/Form/ConfigFormBase.php b/core/lib/Drupal/Core/Form/ConfigFormBase.php
index e7878a7db045..cc0b002d84c2 100644
--- a/core/lib/Drupal/Core/Form/ConfigFormBase.php
+++ b/core/lib/Drupal/Core/Form/ConfigFormBase.php
@@ -3,6 +3,7 @@
 namespace Drupal\Core\Form;
 
 use Drupal\Core\Config\ConfigFactoryInterface;
+use Drupal\Core\Messenger\MessengerTrait;
 use Symfony\Component\DependencyInjection\ContainerInterface;
 
 /**
@@ -10,6 +11,7 @@
  */
 abstract class ConfigFormBase extends FormBase {
   use ConfigFormBaseTrait;
+  use MessengerTrait;
 
   /**
    * Constructs a \Drupal\system\ConfigFormBase object.
@@ -51,7 +53,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message($this->t('The configuration options have been saved.'));
+    $this->messenger()->addStatus($this->t('The configuration options have been saved.'));
   }
 
 }
diff --git a/core/lib/Drupal/Core/Form/FormErrorHandler.php b/core/lib/Drupal/Core/Form/FormErrorHandler.php
index 02457ce6d665..695f023a73bb 100644
--- a/core/lib/Drupal/Core/Form/FormErrorHandler.php
+++ b/core/lib/Drupal/Core/Form/FormErrorHandler.php
@@ -3,6 +3,7 @@
 namespace Drupal\Core\Form;
 
 use Drupal\Component\Utility\NestedArray;
+use Drupal\Core\Messenger\MessengerTrait;
 use Drupal\Core\Render\Element;
 
 /**
@@ -10,6 +11,8 @@
  */
 class FormErrorHandler implements FormErrorHandlerInterface {
 
+  use MessengerTrait;
+
   /**
    * {@inheritdoc}
    */
@@ -39,7 +42,7 @@ protected function displayErrorMessages(array $form, FormStateInterface $form_st
 
     // Loop through all form errors and set an error message.
     foreach ($errors as $error) {
-      $this->drupalSetMessage($error, 'error');
+      $this->messenger()->addMessage($error, 'error');
     }
   }
 
@@ -54,6 +57,7 @@ protected function displayErrorMessages(array $form, FormStateInterface $form_st
    * Grouping example:
    * Assume you have a 'street' element somewhere in a form, which is displayed
    * in a details element 'address'. It might be:
+   *
    * @code
    * $form['street'] = [
    *   '#type' => 'textfield',
@@ -160,13 +164,4 @@ protected function setElementErrorsFromFormState(array &$form, FormStateInterfac
     $elements['#errors'] = $form_state->getError($elements);
   }
 
-  /**
-   * Wraps drupal_set_message().
-   *
-   * @codeCoverageIgnore
-   */
-  protected function drupalSetMessage($message = NULL, $type = 'status', $repeat = FALSE) {
-    drupal_set_message($message, $type, $repeat);
-  }
-
 }
diff --git a/core/modules/action/src/ActionFormBase.php b/core/modules/action/src/ActionFormBase.php
index 46b70ede45a5..db878a945309 100644
--- a/core/modules/action/src/ActionFormBase.php
+++ b/core/modules/action/src/ActionFormBase.php
@@ -132,7 +132,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
    */
   public function save(array $form, FormStateInterface $form_state) {
     $this->entity->save();
-    drupal_set_message($this->t('The action has been successfully saved.'));
+    $this->messenger()->addStatus($this->t('The action has been successfully saved.'));
 
     $form_state->setRedirect('entity.action.collection');
   }
diff --git a/core/modules/action/src/Plugin/Action/MessageAction.php b/core/modules/action/src/Plugin/Action/MessageAction.php
index c85d249b08cb..9309fc926acd 100644
--- a/core/modules/action/src/Plugin/Action/MessageAction.php
+++ b/core/modules/action/src/Plugin/Action/MessageAction.php
@@ -5,6 +5,7 @@
 use Drupal\Core\Access\AccessResult;
 use Drupal\Core\Action\ConfigurableActionBase;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
 use Drupal\Core\Render\RendererInterface;
 use Drupal\Core\Session\AccountInterface;
@@ -36,6 +37,13 @@ class MessageAction extends ConfigurableActionBase implements ContainerFactoryPl
    */
   protected $renderer;
 
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
   /**
    * Constructs a MessageAction object.
    *
@@ -49,19 +57,22 @@ class MessageAction extends ConfigurableActionBase implements ContainerFactoryPl
    *   The token service.
    * @param \Drupal\Core\Render\RendererInterface $renderer
    *   The renderer.
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   The messenger.
    */
-  public function __construct(array $configuration, $plugin_id, $plugin_definition, Token $token, RendererInterface $renderer) {
+  public function __construct(array $configuration, $plugin_id, $plugin_definition, Token $token, RendererInterface $renderer, MessengerInterface $messenger) {
     parent::__construct($configuration, $plugin_id, $plugin_definition);
 
     $this->token = $token;
     $this->renderer = $renderer;
+    $this->messenger = $messenger;
   }
 
   /**
    * {@inheritdoc}
    */
   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
-    return new static($configuration, $plugin_id, $plugin_definition, $container->get('token'), $container->get('renderer'));
+    return new static($configuration, $plugin_id, $plugin_definition, $container->get('token'), $container->get('renderer'), $container->get('messenger'));
   }
 
   /**
@@ -77,7 +88,7 @@ public function execute($entity = NULL) {
     ];
 
     // @todo Fix in https://www.drupal.org/node/2577827
-    drupal_set_message($this->renderer->renderPlain($build));
+    $this->messenger->addStatus($this->renderer->renderPlain($build));
   }
 
   /**
diff --git a/core/modules/aggregator/src/FeedForm.php b/core/modules/aggregator/src/FeedForm.php
index aed2cd19c359..7fc254780bcf 100644
--- a/core/modules/aggregator/src/FeedForm.php
+++ b/core/modules/aggregator/src/FeedForm.php
@@ -22,12 +22,12 @@ public function save(array $form, FormStateInterface $form_state) {
     $label = $feed->label();
     $view_link = $feed->link($label, 'canonical');
     if ($status == SAVED_UPDATED) {
-      drupal_set_message($this->t('The feed %feed has been updated.', ['%feed' => $view_link]));
+      $this->messenger()->addStatus($this->t('The feed %feed has been updated.', ['%feed' => $view_link]));
       $form_state->setRedirectUrl($feed->urlInfo('canonical'));
     }
     else {
       $this->logger('aggregator')->notice('Feed %feed added.', ['%feed' => $feed->label(), 'link' => $this->l($this->t('View'), new Url('aggregator.admin_overview'))]);
-      drupal_set_message($this->t('The feed %feed has been added.', ['%feed' => $view_link]));
+      $this->messenger()->addStatus($this->t('The feed %feed has been added.', ['%feed' => $view_link]));
     }
   }
 
diff --git a/core/modules/aggregator/src/Form/OpmlFeedAdd.php b/core/modules/aggregator/src/Form/OpmlFeedAdd.php
index 60a189936240..7958f5f7ba95 100644
--- a/core/modules/aggregator/src/Form/OpmlFeedAdd.php
+++ b/core/modules/aggregator/src/Form/OpmlFeedAdd.php
@@ -123,14 +123,14 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       }
       catch (RequestException $e) {
         $this->logger('aggregator')->warning('Failed to download OPML file due to "%error".', ['%error' => $e->getMessage()]);
-        drupal_set_message($this->t('Failed to download OPML file due to "%error".', ['%error' => $e->getMessage()]));
+        $this->messenger()->addStatus($this->t('Failed to download OPML file due to "%error".', ['%error' => $e->getMessage()]));
         return;
       }
     }
 
     $feeds = $this->parseOpml($data);
     if (empty($feeds)) {
-      drupal_set_message($this->t('No new feed has been added.'));
+      $this->messenger()->addStatus($this->t('No new feed has been added.'));
       return;
     }
 
@@ -138,7 +138,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     foreach ($feeds as $feed) {
       // Ensure URL is valid.
       if (!UrlHelper::isValid($feed['url'], TRUE)) {
-        drupal_set_message($this->t('The URL %url is invalid.', ['%url' => $feed['url']]), 'warning');
+        $this->messenger()->addWarning($this->t('The URL %url is invalid.', ['%url' => $feed['url']]));
         continue;
       }
 
@@ -153,11 +153,11 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $result = $this->feedStorage->loadMultiple($ids);
       foreach ($result as $old) {
         if (strcasecmp($old->label(), $feed['title']) == 0) {
-          drupal_set_message($this->t('A feed named %title already exists.', ['%title' => $old->label()]), 'warning');
+          $this->messenger()->addWarning($this->t('A feed named %title already exists.', ['%title' => $old->label()]));
           continue 2;
         }
         if (strcasecmp($old->getUrl(), $feed['url']) == 0) {
-          drupal_set_message($this->t('A feed with the URL %url already exists.', ['%url' => $old->getUrl()]), 'warning');
+          $this->messenger()->addWarning($this->t('A feed with the URL %url already exists.', ['%url' => $old->getUrl()]));
           continue 2;
         }
       }
diff --git a/core/modules/aggregator/src/Plugin/aggregator/fetcher/DefaultFetcher.php b/core/modules/aggregator/src/Plugin/aggregator/fetcher/DefaultFetcher.php
index 6c6793a59de7..3df80a325884 100644
--- a/core/modules/aggregator/src/Plugin/aggregator/fetcher/DefaultFetcher.php
+++ b/core/modules/aggregator/src/Plugin/aggregator/fetcher/DefaultFetcher.php
@@ -6,6 +6,7 @@
 use Drupal\aggregator\FeedInterface;
 use Drupal\Component\Datetime\DateTimePlus;
 use Drupal\Core\Http\ClientFactory;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
 use GuzzleHttp\Exception\RequestException;
 use GuzzleHttp\Psr7\Request;
@@ -42,6 +43,13 @@ class DefaultFetcher implements FetcherInterface, ContainerFactoryPluginInterfac
    */
   protected $logger;
 
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
   /**
    * Constructs a DefaultFetcher object.
    *
@@ -49,10 +57,13 @@ class DefaultFetcher implements FetcherInterface, ContainerFactoryPluginInterfac
    *   A Guzzle client object.
    * @param \Psr\Log\LoggerInterface $logger
    *   A logger instance.
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   The messenger.
    */
-  public function __construct(ClientFactory $http_client_factory, LoggerInterface $logger) {
+  public function __construct(ClientFactory $http_client_factory, LoggerInterface $logger, MessengerInterface $messenger) {
     $this->httpClientFactory = $http_client_factory;
     $this->logger = $logger;
+    $this->messenger = $messenger;
   }
 
   /**
@@ -61,7 +72,8 @@ public function __construct(ClientFactory $http_client_factory, LoggerInterface
   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
     return new static(
       $container->get('http_client_factory'),
-      $container->get('logger.factory')->get('aggregator')
+      $container->get('logger.factory')->get('aggregator'),
+      $container->get('messenger')
     );
   }
 
@@ -115,7 +127,7 @@ public function fetch(FeedInterface $feed) {
     }
     catch (RequestException $e) {
       $this->logger->warning('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]);
-      drupal_set_message(t('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]), 'warning');
+      $this->messenger->addWarning(t('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]));
       return FALSE;
     }
   }
diff --git a/core/modules/aggregator/src/Plugin/aggregator/parser/DefaultParser.php b/core/modules/aggregator/src/Plugin/aggregator/parser/DefaultParser.php
index 03fa55f01cc9..2694042104c9 100644
--- a/core/modules/aggregator/src/Plugin/aggregator/parser/DefaultParser.php
+++ b/core/modules/aggregator/src/Plugin/aggregator/parser/DefaultParser.php
@@ -4,6 +4,7 @@
 
 use Drupal\aggregator\Plugin\ParserInterface;
 use Drupal\aggregator\FeedInterface;
+use Drupal\Core\Messenger\MessengerTrait;
 use Zend\Feed\Reader\Reader;
 use Zend\Feed\Reader\Exception\ExceptionInterface;
 
@@ -20,6 +21,8 @@
  */
 class DefaultParser implements ParserInterface {
 
+  use MessengerTrait;
+
   /**
    * {@inheritdoc}
    */
@@ -31,7 +34,7 @@ public function parse(FeedInterface $feed) {
     }
     catch (ExceptionInterface $e) {
       watchdog_exception('aggregator', $e);
-      drupal_set_message(t('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]), 'error');
+      $this->messenger()->addError(t('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]));
 
       return FALSE;
     }
diff --git a/core/modules/aggregator/src/Plugin/aggregator/processor/DefaultProcessor.php b/core/modules/aggregator/src/Plugin/aggregator/processor/DefaultProcessor.php
index 4e8200b87bc2..6a0c9dbbfc83 100644
--- a/core/modules/aggregator/src/Plugin/aggregator/processor/DefaultProcessor.php
+++ b/core/modules/aggregator/src/Plugin/aggregator/processor/DefaultProcessor.php
@@ -3,15 +3,16 @@
 namespace Drupal\aggregator\Plugin\aggregator\processor;
 
 use Drupal\aggregator\Entity\Item;
+use Drupal\aggregator\FeedInterface;
 use Drupal\aggregator\ItemStorageInterface;
 use Drupal\aggregator\Plugin\AggregatorPluginSettingsBase;
 use Drupal\aggregator\Plugin\ProcessorInterface;
-use Drupal\aggregator\FeedInterface;
 use Drupal\Component\Utility\Unicode;
 use Drupal\Core\Config\ConfigFactoryInterface;
 use Drupal\Core\Datetime\DateFormatterInterface;
 use Drupal\Core\Form\ConfigFormBaseTrait;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
 use Drupal\Core\Routing\UrlGeneratorTrait;
 use Symfony\Component\DependencyInjection\ContainerInterface;
@@ -28,6 +29,7 @@
  * )
  */
 class DefaultProcessor extends AggregatorPluginSettingsBase implements ProcessorInterface, ContainerFactoryPluginInterface {
+
   use ConfigFormBaseTrait;
   use UrlGeneratorTrait;
 
@@ -52,6 +54,13 @@ class DefaultProcessor extends AggregatorPluginSettingsBase implements Processor
    */
   protected $dateFormatter;
 
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
   /**
    * Constructs a DefaultProcessor object.
    *
@@ -67,11 +76,14 @@ class DefaultProcessor extends AggregatorPluginSettingsBase implements Processor
    *   The entity storage for feed items.
    * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
    *   The date formatter service.
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   The messenger.
    */
-  public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config, ItemStorageInterface $item_storage, DateFormatterInterface $date_formatter) {
+  public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config, ItemStorageInterface $item_storage, DateFormatterInterface $date_formatter, MessengerInterface $messenger) {
     $this->configFactory = $config;
     $this->itemStorage = $item_storage;
     $this->dateFormatter = $date_formatter;
+    $this->messenger = $messenger;
     // @todo Refactor aggregator plugins to ConfigEntity so merging
     //   the configuration here is not needed.
     parent::__construct($configuration + $this->getConfiguration(), $plugin_id, $plugin_definition);
@@ -87,7 +99,8 @@ public static function create(ContainerInterface $container, array $configuratio
       $plugin_definition,
       $container->get('config.factory'),
       $container->get('entity_type.manager')->getStorage('aggregator_item'),
-      $container->get('date.formatter')
+      $container->get('date.formatter'),
+      $container->get('messenger')
     );
   }
 
@@ -231,7 +244,7 @@ public function delete(FeedInterface $feed) {
       $this->itemStorage->delete($items);
     }
     // @todo This should be moved out to caller with a different message maybe.
-    drupal_set_message(t('The news items from %site have been deleted.', ['%site' => $feed->label()]));
+    $this->messenger->addStatus(t('The news items from %site have been deleted.', ['%site' => $feed->label()]));
   }
 
   /**
diff --git a/core/modules/aggregator/tests/src/Unit/Plugin/AggregatorPluginSettingsBaseTest.php b/core/modules/aggregator/tests/src/Unit/Plugin/AggregatorPluginSettingsBaseTest.php
index 56c0339bd673..ac2d5795c77b 100644
--- a/core/modules/aggregator/tests/src/Unit/Plugin/AggregatorPluginSettingsBaseTest.php
+++ b/core/modules/aggregator/tests/src/Unit/Plugin/AggregatorPluginSettingsBaseTest.php
@@ -4,6 +4,7 @@
 
 use Drupal\aggregator\Form\SettingsForm;
 use Drupal\Core\Form\FormState;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Tests\UnitTestCase;
 
 /**
@@ -55,6 +56,10 @@ protected function setUp() {
         ->will($this->returnValue(['aggregator_test' => ['title' => '', 'description' => '']]));
     }
 
+    /** @var \Drupal\Core\Messenger\MessengerInterface|\PHPUnit_Framework_MockObject_MockBuilder $messenger */
+    $messenger = $this->createMock(MessengerInterface::class);
+    $messenger->expects($this->any())->method('addMessage');
+
     $this->settingsForm = new SettingsForm(
       $this->configFactory,
       $this->managers['fetcher'],
@@ -62,6 +67,7 @@ protected function setUp() {
       $this->managers['processor'],
       $this->getStringTranslationStub()
     );
+    $this->settingsForm->setMessenger($messenger);
   }
 
   /**
@@ -104,11 +110,3 @@ public function testSettingsForm() {
   }
 
 }
-
-// @todo Delete after https://www.drupal.org/node/2278383 is in.
-namespace Drupal\Core\Form;
-
-if (!function_exists('drupal_set_message')) {
-  function drupal_set_message() {
-  }
-}
diff --git a/core/modules/ban/src/Form/BanAdmin.php b/core/modules/ban/src/Form/BanAdmin.php
index 5d8e7957f806..d71be8d40259 100644
--- a/core/modules/ban/src/Form/BanAdmin.php
+++ b/core/modules/ban/src/Form/BanAdmin.php
@@ -120,7 +120,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) {
   public function submitForm(array &$form, FormStateInterface $form_state) {
     $ip = trim($form_state->getValue('ip'));
     $this->ipManager->banIp($ip);
-    drupal_set_message($this->t('The IP address %ip has been banned.', ['%ip' => $ip]));
+    $this->messenger()->addStatus($this->t('The IP address %ip has been banned.', ['%ip' => $ip]));
     $form_state->setRedirect('ban.admin_page');
   }
 
diff --git a/core/modules/ban/src/Form/BanDelete.php b/core/modules/ban/src/Form/BanDelete.php
index 2d5731f13994..9a3ddd48cfd1 100644
--- a/core/modules/ban/src/Form/BanDelete.php
+++ b/core/modules/ban/src/Form/BanDelete.php
@@ -96,7 +96,7 @@ public function buildForm(array $form, FormStateInterface $form_state, $ban_id =
   public function submitForm(array &$form, FormStateInterface $form_state) {
     $this->ipManager->unbanIp($this->banIp);
     $this->logger('user')->notice('Deleted %ip', ['%ip' => $this->banIp]);
-    drupal_set_message($this->t('The IP address %ip was deleted.', ['%ip' => $this->banIp]));
+    $this->messenger()->addStatus($this->t('The IP address %ip was deleted.', ['%ip' => $this->banIp]));
     $form_state->setRedirectUrl($this->getCancelUrl());
   }
 
diff --git a/core/modules/big_pipe/src/Render/BigPipe.php b/core/modules/big_pipe/src/Render/BigPipe.php
index 79aba6f9d64d..e646348d837d 100644
--- a/core/modules/big_pipe/src/Render/BigPipe.php
+++ b/core/modules/big_pipe/src/Render/BigPipe.php
@@ -730,8 +730,8 @@ protected function getPlaceholderOrder($html, $placeholders) {
     // being rendered: any code can add messages to render.
     // This violates the principle that each lazy builder must be able to render
     // itself in isolation, and therefore in any order. However, we cannot
-    // change the way drupal_set_message() works in the Drupal 8 cycle. So we
-    // have to accommodate its special needs.
+    // change the way \Drupal\Core\Messenger\MessengerInterface::addMessage()
+    // works in the Drupal 8 cycle. So we have to accommodate its special needs.
     // Allowing placeholders to be rendered in a particular order (in this case:
     // last) would violate this isolation principle. Thus a monopoly is granted
     // to this one special case, with this hard-coded solution.
diff --git a/core/modules/big_pipe/tests/modules/big_pipe_test/src/BigPipeTestController.php b/core/modules/big_pipe/tests/modules/big_pipe_test/src/BigPipeTestController.php
index a708ecc88267..2405aff5d1c9 100644
--- a/core/modules/big_pipe/tests/modules/big_pipe_test/src/BigPipeTestController.php
+++ b/core/modules/big_pipe/tests/modules/big_pipe_test/src/BigPipeTestController.php
@@ -24,7 +24,7 @@ public function test() {
     if ($has_session) {
       // Only set a message if a session already exists, otherwise we always
       // trigger a session, which means we can't test no-session requests.
-      drupal_set_message('Hello from BigPipe!');
+      \Drupal::messenger()->addStatus('Hello from BigPipe!');
     }
     $build['html'] = $cases['html']->renderArray;
 
diff --git a/core/modules/block/block.module b/core/modules/block/block.module
index ee6a4a11ea53..28fd7b30c631 100644
--- a/core/modules/block/block.module
+++ b/core/modules/block/block.module
@@ -145,7 +145,11 @@ function block_rebuild() {
         // Disable blocks in invalid regions.
         if (!isset($regions[$block->getRegion()])) {
           if ($block->status()) {
-            drupal_set_message(t('The block %info was assigned to the invalid region %region and has been disabled.', ['%info' => $block_id, '%region' => $block->getRegion()]), 'warning');
+            \Drupal::messenger()
+              ->addWarning(t('The block %info was assigned to the invalid region %region and has been disabled.', [
+                '%info' => $block_id,
+                '%region' => $block->getRegion(),
+              ]));
           }
           $block
             ->setRegion(system_default_region($theme))
diff --git a/core/modules/block/src/BlockForm.php b/core/modules/block/src/BlockForm.php
index b409c535979c..64f1aad7754a 100644
--- a/core/modules/block/src/BlockForm.php
+++ b/core/modules/block/src/BlockForm.php
@@ -360,7 +360,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     // Save the settings of the plugin.
     $entity->save();
 
-    drupal_set_message($this->t('The block configuration has been saved.'));
+    $this->messenger()->addStatus($this->t('The block configuration has been saved.'));
     $form_state->setRedirect(
       'block.admin_display_theme',
       [
diff --git a/core/modules/block/src/BlockListBuilder.php b/core/modules/block/src/BlockListBuilder.php
index 37b2e8bfc346..facd02443c1e 100644
--- a/core/modules/block/src/BlockListBuilder.php
+++ b/core/modules/block/src/BlockListBuilder.php
@@ -11,6 +11,7 @@
 use Drupal\Core\Form\FormBuilderInterface;
 use Drupal\Core\Form\FormInterface;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Core\Theme\ThemeManagerInterface;
 use Drupal\Core\Url;
 use Symfony\Component\DependencyInjection\ContainerInterface;
@@ -56,6 +57,13 @@ class BlockListBuilder extends ConfigEntityListBuilder implements FormInterface
    */
   protected $limit = FALSE;
 
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
   /**
    * Constructs a new BlockListBuilder object.
    *
@@ -68,11 +76,12 @@ class BlockListBuilder extends ConfigEntityListBuilder implements FormInterface
    * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
    *   The form builder.
    */
-  public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, ThemeManagerInterface $theme_manager, FormBuilderInterface $form_builder) {
+  public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, ThemeManagerInterface $theme_manager, FormBuilderInterface $form_builder, MessengerInterface $messenger) {
     parent::__construct($entity_type, $storage);
 
     $this->themeManager = $theme_manager;
     $this->formBuilder = $form_builder;
+    $this->messenger = $messenger;
   }
 
   /**
@@ -83,7 +92,8 @@ public static function createInstance(ContainerInterface $container, EntityTypeI
       $entity_type,
       $container->get('entity.manager')->getStorage($entity_type->id()),
       $container->get('theme.manager'),
-      $container->get('form_builder')
+      $container->get('form_builder'),
+      $container->get('messenger')
     );
   }
 
@@ -367,7 +377,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $entity->setRegion($entity_values['region']);
       $entity->save();
     }
-    drupal_set_message(t('The block settings have been updated.'));
+    $this->messenger->addStatus($this->t('The block settings have been updated.'));
 
     // Remove any previously set block placement.
     $this->request->query->remove('block-placement');
diff --git a/core/modules/block/src/Controller/BlockController.php b/core/modules/block/src/Controller/BlockController.php
index 7398ff98e125..543ce59038f8 100644
--- a/core/modules/block/src/Controller/BlockController.php
+++ b/core/modules/block/src/Controller/BlockController.php
@@ -53,7 +53,7 @@ public static function create(ContainerInterface $container) {
    */
   public function performOperation(BlockInterface $block, $op) {
     $block->$op()->save();
-    drupal_set_message($this->t('The block settings have been updated.'));
+    $this->messenger()->addStatus($this->t('The block settings have been updated.'));
     return $this->redirect('block.admin_display');
   }
 
diff --git a/core/modules/block/tests/modules/block_test/src/Controller/TestMultipleFormController.php b/core/modules/block/tests/modules/block_test/src/Controller/TestMultipleFormController.php
index e7aac65500e9..246bcea58f88 100644
--- a/core/modules/block/tests/modules/block_test/src/Controller/TestMultipleFormController.php
+++ b/core/modules/block/tests/modules/block_test/src/Controller/TestMultipleFormController.php
@@ -17,7 +17,8 @@ public function testMultipleForms() {
       'form2' => $this->formBuilder()->buildForm('\Drupal\block_test\Form\FavoriteAnimalTestForm', $form_state),
     ];
 
-    // Output all attached placeholders trough drupal_set_message(), so we can
+    // Output all attached placeholders trough
+    // \Drupal\Core\Messenger\MessengerInterface::addMessage(), so we can
     // see if there's only one in the tests.
     $post_render_callable = function ($elements) {
       $matches = [];
@@ -26,7 +27,7 @@ public function testMultipleForms() {
       $action_values = $matches[2];
 
       foreach ($action_values as $action_value) {
-        drupal_set_message('Form action: ' . $action_value);
+        $this->messenger()->addStatus('Form action: ' . $action_value);
       }
       return $elements;
     };
diff --git a/core/modules/block/tests/modules/block_test/src/Form/FavoriteAnimalTestForm.php b/core/modules/block/tests/modules/block_test/src/Form/FavoriteAnimalTestForm.php
index 3ad55edff2c1..a86db68dfcf3 100644
--- a/core/modules/block/tests/modules/block_test/src/Form/FavoriteAnimalTestForm.php
+++ b/core/modules/block/tests/modules/block_test/src/Form/FavoriteAnimalTestForm.php
@@ -40,7 +40,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message($this->t('Your favorite animal is: @favorite_animal', ['@favorite_animal' => $form['favorite_animal']['#value']]));
+    $this->messenger()->addStatus($this->t('Your favorite animal is: @favorite_animal', ['@favorite_animal' => $form['favorite_animal']['#value']]));
   }
 
 }
diff --git a/core/modules/block/tests/modules/block_test/src/Form/TestForm.php b/core/modules/block/tests/modules/block_test/src/Form/TestForm.php
index 7fa645df5fba..7619d842d140 100644
--- a/core/modules/block/tests/modules/block_test/src/Form/TestForm.php
+++ b/core/modules/block/tests/modules/block_test/src/Form/TestForm.php
@@ -49,7 +49,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message($this->t('Your email address is @email', ['@email' => $form['email']['#value']]));
+    $this->messenger()->addStatus($this->t('Your email address is @email', ['@email' => $form['email']['#value']]));
   }
 
 }
diff --git a/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php b/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php
index 7db350da8133..70afd54ceafb 100644
--- a/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php
+++ b/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php
@@ -3,6 +3,7 @@
 namespace Drupal\block_test\Plugin\Block;
 
 use Drupal\Core\Block\BlockBase;
+use Drupal\Core\Messenger\MessengerTrait;
 use Drupal\Core\Session\AccountInterface;
 use Drupal\user\UserInterface;
 
@@ -19,6 +20,8 @@
  */
 class TestContextAwareBlock extends BlockBase {
 
+  use MessengerTrait;
+
   /**
    * {@inheritdoc}
    */
@@ -37,7 +40,7 @@ public function build() {
    */
   protected function blockAccess(AccountInterface $account) {
     if ($this->getContextValue('user') instanceof UserInterface) {
-      drupal_set_message('User context found.');
+      $this->messenger()->addStatus('User context found.');
     }
 
     return parent::blockAccess($account);
diff --git a/core/modules/block/tests/src/Kernel/BlockRebuildTest.php b/core/modules/block/tests/src/Kernel/BlockRebuildTest.php
index 33de12ce87d8..2443c21052ff 100644
--- a/core/modules/block/tests/src/Kernel/BlockRebuildTest.php
+++ b/core/modules/block/tests/src/Kernel/BlockRebuildTest.php
@@ -47,7 +47,8 @@ public static function setUpBeforeClass() {
    */
   public function testRebuildNoBlocks() {
     block_rebuild();
-    $messages = drupal_get_messages();
+    $messages = \Drupal::messenger()->all();
+    \Drupal::messenger()->deleteAll();
     $this->assertEquals([], $messages);
   }
 
@@ -58,7 +59,8 @@ public function testRebuildNoInvalidBlocks() {
     $this->placeBlock('system_powered_by_block', ['region' => 'content']);
 
     block_rebuild();
-    $messages = drupal_get_messages();
+    $messages = \Drupal::messenger()->all();
+    \Drupal::messenger()->deleteAll();
     $this->assertEquals([], $messages);
   }
 
@@ -89,7 +91,8 @@ public function testRebuildInvalidBlocks() {
     $block1 = Block::load($block1->id());
     $block2 = Block::load($block2->id());
 
-    $messages = drupal_get_messages();
+    $messages = \Drupal::messenger()->all();
+    \Drupal::messenger()->deleteAll();
     $expected = ['warning' => [new TranslatableMarkup('The block %info was assigned to the invalid region %region and has been disabled.', ['%info' => $block1->id(), '%region' => 'INVALID'])]];
     $this->assertEquals($expected, $messages);
 
diff --git a/core/modules/block_content/src/BlockContentForm.php b/core/modules/block_content/src/BlockContentForm.php
index 225dc91b4671..9df2a87d732b 100644
--- a/core/modules/block_content/src/BlockContentForm.php
+++ b/core/modules/block_content/src/BlockContentForm.php
@@ -54,11 +54,11 @@ public function save(array $form, FormStateInterface $form_state) {
 
     if ($insert) {
       $logger->notice('@type: added %info.', $context);
-      drupal_set_message($this->t('@type %info has been created.', $t_args));
+      $this->messenger()->addStatus($this->t('@type %info has been created.', $t_args));
     }
     else {
       $logger->notice('@type: updated %info.', $context);
-      drupal_set_message($this->t('@type %info has been updated.', $t_args));
+      $this->messenger()->addStatus($this->t('@type %info has been updated.', $t_args));
     }
 
     if ($block->id()) {
@@ -83,7 +83,7 @@ public function save(array $form, FormStateInterface $form_state) {
     else {
       // In the unlikely case something went wrong on save, the block will be
       // rebuilt and block form redisplayed.
-      drupal_set_message($this->t('The block could not be saved.'), 'error');
+      $this->messenger()->addError($this->t('The block could not be saved.'));
       $form_state->setRebuild();
     }
   }
diff --git a/core/modules/block_content/src/BlockContentTypeForm.php b/core/modules/block_content/src/BlockContentTypeForm.php
index 00098d3cf3b4..711cda678b7e 100644
--- a/core/modules/block_content/src/BlockContentTypeForm.php
+++ b/core/modules/block_content/src/BlockContentTypeForm.php
@@ -100,12 +100,12 @@ public function save(array $form, FormStateInterface $form_state) {
     $edit_link = $this->entity->link($this->t('Edit'));
     $logger = $this->logger('block_content');
     if ($status == SAVED_UPDATED) {
-      drupal_set_message(t('Custom block type %label has been updated.', ['%label' => $block_type->label()]));
+      $this->messenger()->addStatus(t('Custom block type %label has been updated.', ['%label' => $block_type->label()]));
       $logger->notice('Custom block type %label has been updated.', ['%label' => $block_type->label(), 'link' => $edit_link]);
     }
     else {
       block_content_add_body_field($block_type->id());
-      drupal_set_message(t('Custom block type %label has been added.', ['%label' => $block_type->label()]));
+      $this->messenger()->addStatus(t('Custom block type %label has been added.', ['%label' => $block_type->label()]));
       $logger->notice('Custom block type %label has been added.', ['%label' => $block_type->label(), 'link' => $edit_link]);
     }
 
diff --git a/core/modules/book/src/Controller/BookController.php b/core/modules/book/src/Controller/BookController.php
index b92c3e3fcfeb..fa34d9271128 100644
--- a/core/modules/book/src/Controller/BookController.php
+++ b/core/modules/book/src/Controller/BookController.php
@@ -154,7 +154,7 @@ public function bookExport($type, NodeInterface $node) {
 
     // @todo Convert the custom export functionality to serializer.
     if (!method_exists($this->bookExport, $method)) {
-      drupal_set_message(t('Unknown export format.'));
+      $this->messenger()->addStatus(t('Unknown export format.'));
       throw new NotFoundHttpException();
     }
 
diff --git a/core/modules/book/src/Form/BookAdminEditForm.php b/core/modules/book/src/Form/BookAdminEditForm.php
index 66e717eaba62..e052b7cff1d9 100644
--- a/core/modules/book/src/Form/BookAdminEditForm.php
+++ b/core/modules/book/src/Form/BookAdminEditForm.php
@@ -127,7 +127,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       }
     }
 
-    drupal_set_message($this->t('Updated book %title.', ['%title' => $form['#node']->label()]));
+    $this->messenger()->addStatus($this->t('Updated book %title.', ['%title' => $form['#node']->label()]));
   }
 
   /**
diff --git a/core/modules/book/src/Form/BookOutlineForm.php b/core/modules/book/src/Form/BookOutlineForm.php
index f7ea043ed2eb..1ce771e0de25 100644
--- a/core/modules/book/src/Form/BookOutlineForm.php
+++ b/core/modules/book/src/Form/BookOutlineForm.php
@@ -113,7 +113,7 @@ public function save(array $form, FormStateInterface $form_state) {
     );
     $book_link = $form_state->getValue('book');
     if (!$book_link['bid']) {
-      drupal_set_message($this->t('No changes were made'));
+      $this->messenger()->addStatus($this->t('No changes were made'));
       return;
     }
 
@@ -121,15 +121,15 @@ public function save(array $form, FormStateInterface $form_state) {
     if ($this->bookManager->updateOutline($this->entity)) {
       if (isset($this->entity->book['parent_mismatch']) && $this->entity->book['parent_mismatch']) {
         // This will usually only happen when JS is disabled.
-        drupal_set_message($this->t('The post has been added to the selected book. You may now position it relative to other pages.'));
+        $this->messenger()->addStatus($this->t('The post has been added to the selected book. You may now position it relative to other pages.'));
         $form_state->setRedirectUrl($this->entity->urlInfo('book-outline-form'));
       }
       else {
-        drupal_set_message($this->t('The book outline has been updated.'));
+        $this->messenger()->addStatus($this->t('The book outline has been updated.'));
       }
     }
     else {
-      drupal_set_message($this->t('There was an error adding the post to the book.'), 'error');
+      $this->messenger()->addError($this->t('There was an error adding the post to the book.'));
     }
   }
 
diff --git a/core/modules/book/src/Form/BookRemoveForm.php b/core/modules/book/src/Form/BookRemoveForm.php
index f61aa775a5ab..2d5a91982f7c 100644
--- a/core/modules/book/src/Form/BookRemoveForm.php
+++ b/core/modules/book/src/Form/BookRemoveForm.php
@@ -103,7 +103,7 @@ public function getCancelUrl() {
   public function submitForm(array &$form, FormStateInterface $form_state) {
     if ($this->bookManager->checkNodeIsRemovable($this->node)) {
       $this->bookManager->deleteFromBook($this->node->id());
-      drupal_set_message($this->t('The post has been removed from the book.'));
+      $this->messenger()->addStatus($this->t('The post has been removed from the book.'));
     }
     $form_state->setRedirectUrl($this->getCancelUrl());
   }
diff --git a/core/modules/book/tests/modules/book_test/book_test.module b/core/modules/book/tests/modules/book_test/book_test.module
index 939e75628bee..91da82c28923 100644
--- a/core/modules/book/tests/modules/book_test/book_test.module
+++ b/core/modules/book/tests/modules/book_test/book_test.module
@@ -17,6 +17,6 @@
 function book_test_page_attachments(array &$page) {
   $page['#cache']['tags'][] = 'book_test.debug_book_navigation_cache_context';
   if (\Drupal::state()->get('book_test.debug_book_navigation_cache_context', FALSE)) {
-    drupal_set_message(\Drupal::service('cache_contexts_manager')->convertTokensToKeys(['route.book_navigation'])->getKeys()[0]);
+    \Drupal::messenger()->addStatus(\Drupal::service('cache_contexts_manager')->convertTokensToKeys(['route.book_navigation'])->getKeys()[0]);
   }
 }
diff --git a/core/modules/color/color.module b/core/modules/color/color.module
index 9ca7870a5bac..35552961774d 100644
--- a/core/modules/color/color.module
+++ b/core/modules/color/color.module
@@ -415,7 +415,7 @@ function color_scheme_form_submit($form, FormStateInterface $form_state) {
     $memory_limit = ini_get('memory_limit');
     $size = Bytes::toInt($memory_limit);
     if (!Environment::checkMemoryLimit($usage + $required, $memory_limit)) {
-      drupal_set_message(t('There is not enough memory available to PHP to change this theme\'s color scheme. You need at least %size more. Check the <a href="http://php.net/manual/ini.core.php#ini.sect.resource-limits">PHP documentation</a> for more information.', ['%size' => format_size($usage + $required - $size)]), 'error');
+      \Drupal::messenger()->addError(t('There is not enough memory available to PHP to change this theme\'s color scheme. You need at least %size more. Check the <a href="http://php.net/manual/ini.core.php#ini.sect.resource-limits">PHP documentation</a> for more information.', ['%size' => format_size($usage + $required - $size)]));
       return;
     }
   }
diff --git a/core/modules/comment/src/CommentForm.php b/core/modules/comment/src/CommentForm.php
index 98e9ddef96da..00647ad0422b 100644
--- a/core/modules/comment/src/CommentForm.php
+++ b/core/modules/comment/src/CommentForm.php
@@ -375,11 +375,11 @@ public function save(array $form, FormStateInterface $form_state) {
       // Explain the approval queue if necessary.
       if (!$comment->isPublished()) {
         if (!$this->currentUser->hasPermission('administer comments')) {
-          drupal_set_message($this->t('Your comment has been queued for review by site administrators and will be published after approval.'));
+          $this->messenger()->addStatus($this->t('Your comment has been queued for review by site administrators and will be published after approval.'));
         }
       }
       else {
-        drupal_set_message($this->t('Your comment has been posted.'));
+        $this->messenger()->addStatus($this->t('Your comment has been posted.'));
       }
       $query = [];
       // Find the current display page for this comment.
@@ -394,7 +394,7 @@ public function save(array $form, FormStateInterface $form_state) {
     }
     else {
       $logger->warning('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]);
-      drupal_set_message($this->t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]), 'error');
+      $this->messenger()->addError($this->t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]));
       // Redirect the user to the entity they are commenting on.
     }
     $form_state->setRedirectUrl($uri);
diff --git a/core/modules/comment/src/CommentTypeForm.php b/core/modules/comment/src/CommentTypeForm.php
index 0ac5b446bd55..401ce8f25f61 100644
--- a/core/modules/comment/src/CommentTypeForm.php
+++ b/core/modules/comment/src/CommentTypeForm.php
@@ -160,12 +160,12 @@ public function save(array $form, FormStateInterface $form_state) {
 
     $edit_link = $this->entity->link($this->t('Edit'));
     if ($status == SAVED_UPDATED) {
-      drupal_set_message(t('Comment type %label has been updated.', ['%label' => $comment_type->label()]));
+      $this->messenger()->addStatus(t('Comment type %label has been updated.', ['%label' => $comment_type->label()]));
       $this->logger->notice('Comment type %label has been updated.', ['%label' => $comment_type->label(), 'link' => $edit_link]);
     }
     else {
       $this->commentManager->addBodyField($comment_type->id());
-      drupal_set_message(t('Comment type %label has been added.', ['%label' => $comment_type->label()]));
+      $this->messenger()->addStatus(t('Comment type %label has been added.', ['%label' => $comment_type->label()]));
       $this->logger->notice('Comment type %label has been added.', ['%label' => $comment_type->label(), 'link' => $edit_link]);
     }
 
diff --git a/core/modules/comment/src/Controller/CommentController.php b/core/modules/comment/src/Controller/CommentController.php
index 560233889ccc..526c31c90830 100644
--- a/core/modules/comment/src/Controller/CommentController.php
+++ b/core/modules/comment/src/Controller/CommentController.php
@@ -85,7 +85,7 @@ public function commentApprove(CommentInterface $comment) {
     $comment->setPublished(TRUE);
     $comment->save();
 
-    drupal_set_message($this->t('Comment approved.'));
+    $this->messenger()->addStatus($this->t('Comment approved.'));
     $permalink_uri = $comment->permalink();
     $permalink_uri->setAbsolute();
     return new RedirectResponse($permalink_uri->toString());
diff --git a/core/modules/comment/src/Form/CommentAdminOverview.php b/core/modules/comment/src/Form/CommentAdminOverview.php
index 8a93ecd85697..3b97d0d1c48b 100644
--- a/core/modules/comment/src/Form/CommentAdminOverview.php
+++ b/core/modules/comment/src/Form/CommentAdminOverview.php
@@ -279,7 +279,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
         }
         $comment->save();
       }
-      drupal_set_message($this->t('The update has been performed.'));
+      $this->messenger()->addStatus($this->t('The update has been performed.'));
       $form_state->setRedirect('comment.admin');
     }
     else {
diff --git a/core/modules/comment/tests/src/Unit/Plugin/views/field/CommentBulkFormTest.php b/core/modules/comment/tests/src/Unit/Plugin/views/field/CommentBulkFormTest.php
index 4e86bb7ef032..8653ca3b85c8 100644
--- a/core/modules/comment/tests/src/Unit/Plugin/views/field/CommentBulkFormTest.php
+++ b/core/modules/comment/tests/src/Unit/Plugin/views/field/CommentBulkFormTest.php
@@ -54,6 +54,8 @@ public function testConstructor() {
 
     $language_manager = $this->getMock('Drupal\Core\Language\LanguageManagerInterface');
 
+    $messenger = $this->getMock('Drupal\Core\Messenger\MessengerInterface');
+
     $views_data = $this->getMockBuilder('Drupal\views\ViewsData')
       ->disableOriginalConstructor()
       ->getMock();
@@ -84,7 +86,7 @@ public function testConstructor() {
     $definition['title'] = '';
     $options = [];
 
-    $comment_bulk_form = new CommentBulkForm([], 'comment_bulk_form', $definition, $entity_manager, $language_manager);
+    $comment_bulk_form = new CommentBulkForm([], 'comment_bulk_form', $definition, $entity_manager, $language_manager, $messenger);
     $comment_bulk_form->init($executable, $display, $options);
 
     $this->assertAttributeEquals(array_slice($actions, 0, -1, TRUE), 'actions', $comment_bulk_form);
diff --git a/core/modules/config/src/Form/ConfigImportForm.php b/core/modules/config/src/Form/ConfigImportForm.php
index 6b7b557c1556..28852f24eaa9 100644
--- a/core/modules/config/src/Form/ConfigImportForm.php
+++ b/core/modules/config/src/Form/ConfigImportForm.php
@@ -55,7 +55,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
     $directory = config_get_config_directory(CONFIG_SYNC_DIRECTORY);
     $directory_is_writable = is_writable($directory);
     if (!$directory_is_writable) {
-      drupal_set_message($this->t('The directory %directory is not writable.', ['%directory' => $directory]), 'error');
+      $this->messenger()->addError($this->t('The directory %directory is not writable.', ['%directory' => $directory]));
     }
     $form['import_tarball'] = [
       '#type' => 'file',
@@ -100,11 +100,11 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
           $files[] = $file['filename'];
         }
         $archiver->extractList($files, config_get_config_directory(CONFIG_SYNC_DIRECTORY));
-        drupal_set_message($this->t('Your configuration files were successfully uploaded and are ready for import.'));
+        $this->messenger()->addStatus($this->t('Your configuration files were successfully uploaded and are ready for import.'));
         $form_state->setRedirect('config.sync');
       }
       catch (\Exception $e) {
-        drupal_set_message($this->t('Could not extract the contents of the tar file. The error message is <em>@message</em>', ['@message' => $e->getMessage()]), 'error');
+        $this->messenger()->addError($this->t('Could not extract the contents of the tar file. The error message is <em>@message</em>', ['@message' => $e->getMessage()]));
       }
       drupal_unlink($path);
     }
diff --git a/core/modules/config/src/Form/ConfigSingleImportForm.php b/core/modules/config/src/Form/ConfigSingleImportForm.php
index 9f9a8d9281a7..560f124c840d 100644
--- a/core/modules/config/src/Form/ConfigSingleImportForm.php
+++ b/core/modules/config/src/Form/ConfigSingleImportForm.php
@@ -395,7 +395,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     /** @var \Drupal\Core\Config\ConfigImporter $config_importer */
     $config_importer = $form_state->get('config_importer');
     if ($config_importer->alreadyImporting()) {
-      drupal_set_message($this->t('Another request may be importing configuration already.'), 'error');
+      $this->messenger()->addError($this->t('Another request may be importing configuration already.'));
     }
     else {
       try {
@@ -416,9 +416,9 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       }
       catch (ConfigImporterException $e) {
         // There are validation errors.
-        drupal_set_message($this->t('The configuration import failed for the following reasons:'), 'error');
+        $this->messenger()->addError($this->t('The configuration import failed for the following reasons:'));
         foreach ($config_importer->getErrors() as $message) {
-          drupal_set_message($message, 'error');
+          $this->messenger()->addError($message);
         }
       }
     }
diff --git a/core/modules/config/src/Form/ConfigSync.php b/core/modules/config/src/Form/ConfigSync.php
index f71d6d5a460a..c82467947af2 100644
--- a/core/modules/config/src/Form/ConfigSync.php
+++ b/core/modules/config/src/Form/ConfigSync.php
@@ -191,7 +191,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
       return $form;
     }
     elseif (!$storage_comparer->validateSiteUuid()) {
-      drupal_set_message($this->t('The staged configuration cannot be imported, because it originates from a different site than this site. You can only synchronize configuration between cloned instances of this site.'), 'error');
+      $this->messenger()->addError($this->t('The staged configuration cannot be imported, because it originates from a different site than this site. You can only synchronize configuration between cloned instances of this site.'));
       $form['actions']['#access'] = FALSE;
       return $form;
     }
@@ -221,7 +221,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
             '#items' => $change_list,
           ]
         ];
-        drupal_set_message($this->renderer->renderPlain($message), 'warning');
+        $this->messenger()->addWarning($this->renderer->renderPlain($message));
       }
     }
 
@@ -330,7 +330,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $this->getStringTranslation()
     );
     if ($config_importer->alreadyImporting()) {
-      drupal_set_message($this->t('Another request may be synchronizing configuration already.'));
+      $this->messenger()->addStatus($this->t('Another request may be synchronizing configuration already.'));
     }
     else {
       try {
@@ -351,9 +351,9 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       }
       catch (ConfigImporterException $e) {
         // There are validation errors.
-        drupal_set_message($this->t('The configuration cannot be imported because it failed validation for the following reasons:'), 'error');
+        $this->messenger()->addError($this->t('The configuration cannot be imported because it failed validation for the following reasons:'));
         foreach ($config_importer->getErrors() as $message) {
-          drupal_set_message($message, 'error');
+          $this->messenger()->addError($message);
         }
       }
     }
@@ -394,13 +394,13 @@ public static function finishBatch($success, $results, $operations) {
     if ($success) {
       if (!empty($results['errors'])) {
         foreach ($results['errors'] as $error) {
-          drupal_set_message($error, 'error');
+          \Drupal::messenger()->addError($error);
           \Drupal::logger('config_sync')->error($error);
         }
-        drupal_set_message(\Drupal::translation()->translate('The configuration was imported with errors.'), 'warning');
+        \Drupal::messenger()->addWarning(\Drupal::translation()->translate('The configuration was imported with errors.'));
       }
       else {
-        drupal_set_message(\Drupal::translation()->translate('The configuration was imported successfully.'));
+        \Drupal::messenger()->addStatus(\Drupal::translation()->translate('The configuration was imported successfully.'));
       }
     }
     else {
@@ -408,7 +408,7 @@ public static function finishBatch($success, $results, $operations) {
       // $operations contains the operations that remained unprocessed.
       $error_operation = reset($operations);
       $message = \Drupal::translation()->translate('An error occurred while processing %error_operation with arguments: @arguments', ['%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)]);
-      drupal_set_message($message, 'error');
+      \Drupal::messenger()->addError($message);
     }
   }
 
diff --git a/core/modules/config/tests/config_test/src/ConfigTestForm.php b/core/modules/config/tests/config_test/src/ConfigTestForm.php
index fbc0f9661d5f..86e021e38c2c 100644
--- a/core/modules/config/tests/config_test/src/ConfigTestForm.php
+++ b/core/modules/config/tests/config_test/src/ConfigTestForm.php
@@ -138,10 +138,10 @@ public function save(array $form, FormStateInterface $form_state) {
     $status = $entity->save();
 
     if ($status === SAVED_UPDATED) {
-      drupal_set_message(format_string('%label configuration has been updated.', ['%label' => $entity->label()]));
+      $this->messenger()->addStatus(format_string('%label configuration has been updated.', ['%label' => $entity->label()]));
     }
     else {
-      drupal_set_message(format_string('%label configuration has been created.', ['%label' => $entity->label()]));
+      $this->messenger()->addStatus(format_string('%label configuration has been created.', ['%label' => $entity->label()]));
     }
 
     $form_state->setRedirectUrl($this->entity->urlInfo('collection'));
diff --git a/core/modules/config_translation/src/Controller/ConfigTranslationController.php b/core/modules/config_translation/src/Controller/ConfigTranslationController.php
index a8c426ae0e64..b4d335656915 100644
--- a/core/modules/config_translation/src/Controller/ConfigTranslationController.php
+++ b/core/modules/config_translation/src/Controller/ConfigTranslationController.php
@@ -139,7 +139,7 @@ public function itemPage(Request $request, RouteMatchInterface $route_match, $pl
 
     $languages = $this->languageManager->getLanguages();
     if (count($languages) == 1) {
-      drupal_set_message($this->t('In order to translate configuration, the website must have at least two <a href=":url">languages</a>.', [':url' => $this->url('entity.configurable_language.collection')]), 'warning');
+      $this->messenger()->addWarning($this->t('In order to translate configuration, the website must have at least two <a href=":url">languages</a>.', [':url' => $this->url('entity.configurable_language.collection')]));
     }
 
     try {
@@ -162,7 +162,7 @@ public function itemPage(Request $request, RouteMatchInterface $route_match, $pl
           '#items' => $items,
         ],
       ];
-      drupal_set_message($this->renderer->renderPlain($message), 'warning');
+      $this->messenger()->addWarning($this->renderer->renderPlain($message));
 
       $original_langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
       $operations_access = FALSE;
diff --git a/core/modules/config_translation/src/Form/ConfigTranslationAddForm.php b/core/modules/config_translation/src/Form/ConfigTranslationAddForm.php
index 812b1a11bb9d..8b3f4a896636 100644
--- a/core/modules/config_translation/src/Form/ConfigTranslationAddForm.php
+++ b/core/modules/config_translation/src/Form/ConfigTranslationAddForm.php
@@ -36,7 +36,7 @@ public function buildForm(array $form, FormStateInterface $form_state, RouteMatc
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
     parent::submitForm($form, $form_state);
-    drupal_set_message($this->t('Successfully saved @language translation.', ['@language' => $this->language->getName()]));
+    $this->messenger()->addStatus($this->t('Successfully saved @language translation.', ['@language' => $this->language->getName()]));
   }
 
 }
diff --git a/core/modules/config_translation/src/Form/ConfigTranslationDeleteForm.php b/core/modules/config_translation/src/Form/ConfigTranslationDeleteForm.php
index 273b26c9e554..d420ee63dc5c 100644
--- a/core/modules/config_translation/src/Form/ConfigTranslationDeleteForm.php
+++ b/core/modules/config_translation/src/Form/ConfigTranslationDeleteForm.php
@@ -142,7 +142,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $cache_backend->deleteAll();
     }
 
-    drupal_set_message($this->t('@language translation of %label was deleted', ['%label' => $this->mapper->getTitle(), '@language' => $this->language->getName()]));
+    $this->messenger()->addStatus($this->t('@language translation of %label was deleted', ['%label' => $this->mapper->getTitle(), '@language' => $this->language->getName()]));
 
     $form_state->setRedirectUrl($this->getCancelUrl());
   }
diff --git a/core/modules/config_translation/src/Form/ConfigTranslationEditForm.php b/core/modules/config_translation/src/Form/ConfigTranslationEditForm.php
index cdbd9b898c56..8754d916509b 100644
--- a/core/modules/config_translation/src/Form/ConfigTranslationEditForm.php
+++ b/core/modules/config_translation/src/Form/ConfigTranslationEditForm.php
@@ -36,7 +36,7 @@ public function buildForm(array $form, FormStateInterface $form_state, RouteMatc
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
     parent::submitForm($form, $form_state);
-    drupal_set_message($this->t('Successfully updated @language translation.', ['@language' => $this->language->getName()]));
+    $this->messenger()->addStatus($this->t('Successfully updated @language translation.', ['@language' => $this->language->getName()]));
   }
 
 }
diff --git a/core/modules/contact/src/ContactFormEditForm.php b/core/modules/contact/src/ContactFormEditForm.php
index 1df695337b20..7e78f7835da2 100644
--- a/core/modules/contact/src/ContactFormEditForm.php
+++ b/core/modules/contact/src/ContactFormEditForm.php
@@ -167,11 +167,11 @@ public function save(array $form, FormStateInterface $form_state) {
     $edit_link = $this->entity->link($this->t('Edit'));
     $view_link = $contact_form->link($contact_form->label(), 'canonical');
     if ($status == SAVED_UPDATED) {
-      drupal_set_message($this->t('Contact form %label has been updated.', ['%label' => $view_link]));
+      $this->messenger()->addStatus($this->t('Contact form %label has been updated.', ['%label' => $view_link]));
       $this->logger('contact')->notice('Contact form %label has been updated.', ['%label' => $contact_form->label(), 'link' => $edit_link]);
     }
     else {
-      drupal_set_message($this->t('Contact form %label has been added.', ['%label' => $view_link]));
+      $this->messenger()->addStatus($this->t('Contact form %label has been added.', ['%label' => $view_link]));
       $this->logger('contact')->notice('Contact form %label has been added.', ['%label' => $contact_form->label(), 'link' => $edit_link]);
     }
 
diff --git a/core/modules/contact/src/Controller/ContactController.php b/core/modules/contact/src/Controller/ContactController.php
index 35655342f62c..1844280f5537 100644
--- a/core/modules/contact/src/Controller/ContactController.php
+++ b/core/modules/contact/src/Controller/ContactController.php
@@ -64,9 +64,9 @@ public function contactSitePage(ContactFormInterface $contact_form = NULL) {
       // If there are no forms, do not display the form.
       if (empty($contact_form)) {
         if ($this->currentUser()->hasPermission('administer contact forms')) {
-          drupal_set_message($this->t('The contact form has not been configured. <a href=":add">Add one or more forms</a> .', [
+          $this->messenger()->addError($this->t('The contact form has not been configured. <a href=":add">Add one or more forms</a> .', [
             ':add' => $this->url('contact.form_add'),
-          ]), 'error');
+          ]));
           return [];
         }
         else {
diff --git a/core/modules/contact/src/MessageForm.php b/core/modules/contact/src/MessageForm.php
index c555f3bcec05..3c4030c2ab1b 100644
--- a/core/modules/contact/src/MessageForm.php
+++ b/core/modules/contact/src/MessageForm.php
@@ -224,7 +224,7 @@ public function save(array $form, FormStateInterface $form_state) {
 
     $this->flood->register('contact', $this->config('contact.settings')->get('flood.interval'));
     if ($submission_message = $contact_form->getMessage()) {
-      drupal_set_message($submission_message);
+      $this->messenger()->addStatus($submission_message);
     }
 
     // To avoid false error messages caused by flood control, redirect away from
diff --git a/core/modules/content_moderation/src/Form/EntityModerationForm.php b/core/modules/content_moderation/src/Form/EntityModerationForm.php
index 98f6fdf2b9a0..0674b68d44c9 100644
--- a/core/modules/content_moderation/src/Form/EntityModerationForm.php
+++ b/core/modules/content_moderation/src/Form/EntityModerationForm.php
@@ -153,7 +153,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     }
     $entity->save();
 
-    drupal_set_message($this->t('The moderation state has been updated.'));
+    $this->messenger()->addStatus($this->t('The moderation state has been updated.'));
 
     $new_state = $this->moderationInfo->getWorkflowForEntity($entity)->getTypePlugin()->getState($new_state);
     // The page we're on likely won't be visible if we just set the entity to
diff --git a/core/modules/content_moderation/src/Plugin/Action/ModerationOptOutPublish.php b/core/modules/content_moderation/src/Plugin/Action/ModerationOptOutPublish.php
index d09c6a5f46c0..1311bdb2f3fd 100644
--- a/core/modules/content_moderation/src/Plugin/Action/ModerationOptOutPublish.php
+++ b/core/modules/content_moderation/src/Plugin/Action/ModerationOptOutPublish.php
@@ -6,6 +6,7 @@
 use Drupal\Core\Action\Plugin\Action\PublishAction;
 use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
 use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
 use Drupal\Core\Session\AccountInterface;
 use Drupal\content_moderation\ModerationInformationInterface;
@@ -32,6 +33,13 @@ class ModerationOptOutPublish extends PublishAction implements ContainerFactoryP
    */
   protected $bundleInfo;
 
+  /**
+   * Messenger service.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
   /**
    * ModerationOptOutPublish constructor.
    *
@@ -47,11 +55,14 @@ class ModerationOptOutPublish extends PublishAction implements ContainerFactoryP
    *   The moderation information service.
    * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info
    *   Bundle info service.
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   Messenger service.
    */
-  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModerationInformationInterface $moderation_info, EntityTypeBundleInfoInterface $bundle_info) {
+  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModerationInformationInterface $moderation_info, EntityTypeBundleInfoInterface $bundle_info, MessengerInterface $messenger) {
     parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager);
     $this->moderationInfo = $moderation_info;
     $this->bundleInfo = $bundle_info;
+    $this->messenger = $messenger;
   }
 
   /**
@@ -62,7 +73,8 @@ public static function create(ContainerInterface $container, array $configuratio
       $configuration, $plugin_id, $plugin_definition,
       $container->get('entity_type.manager'),
       $container->get('content_moderation.moderation_information'),
-      $container->get('entity_type.bundle.info')
+      $container->get('entity_type.bundle.info'),
+      $container->get('messenger')
     );
   }
 
@@ -74,7 +86,10 @@ public function access($entity, AccountInterface $account = NULL, $return_as_obj
     if ($entity && $this->moderationInfo->isModeratedEntity($entity)) {
       $bundle_info = $this->bundleInfo->getBundleInfo($entity->getEntityTypeId());
       $bundle_label = $bundle_info[$entity->bundle()]['label'];
-      drupal_set_message($this->t("@bundle @label were skipped as they are under moderation and may not be directly published.", ['@bundle' => $bundle_label, '@label' => $entity->getEntityType()->getPluralLabel()]), 'warning');
+      $this->messenger->addWarning($this->t("@bundle @label were skipped as they are under moderation and may not be directly published.", [
+        '@bundle' => $bundle_label,
+        '@label' => $entity->getEntityType()->getPluralLabel(),
+      ]));
       $result = AccessResult::forbidden('Cannot directly publish moderated entities.');
       return $return_as_object ? $result : $result->isAllowed();
     }
diff --git a/core/modules/content_moderation/src/Plugin/Action/ModerationOptOutUnpublish.php b/core/modules/content_moderation/src/Plugin/Action/ModerationOptOutUnpublish.php
index 7f9fa83bb341..3dc764dcc0a4 100644
--- a/core/modules/content_moderation/src/Plugin/Action/ModerationOptOutUnpublish.php
+++ b/core/modules/content_moderation/src/Plugin/Action/ModerationOptOutUnpublish.php
@@ -6,6 +6,7 @@
 use Drupal\Core\Action\Plugin\Action\UnpublishAction;
 use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
 use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
 use Drupal\Core\Session\AccountInterface;
 use Drupal\content_moderation\ModerationInformationInterface;
@@ -32,6 +33,13 @@ class ModerationOptOutUnpublish extends UnpublishAction implements ContainerFact
    */
   protected $bundleInfo;
 
+  /**
+   * Messenger service.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
   /**
    * ModerationOptOutUnpublish constructor.
    *
@@ -47,11 +55,14 @@ class ModerationOptOutUnpublish extends UnpublishAction implements ContainerFact
    *   The moderation information service.
    * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info
    *   Bundle info service.
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   Messenger service.
    */
-  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModerationInformationInterface $moderation_info, EntityTypeBundleInfoInterface $bundle_info) {
+  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModerationInformationInterface $moderation_info, EntityTypeBundleInfoInterface $bundle_info, MessengerInterface $messenger) {
     parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager);
     $this->moderationInfo = $moderation_info;
     $this->bundleInfo = $bundle_info;
+    $this->messenger = $messenger;
   }
 
   /**
@@ -62,7 +73,8 @@ public static function create(ContainerInterface $container, array $configuratio
       $configuration, $plugin_id, $plugin_definition,
       $container->get('entity_type.manager'),
       $container->get('content_moderation.moderation_information'),
-      $container->get('entity_type.bundle.info')
+      $container->get('entity_type.bundle.info'),
+      $container->get('messenger')
     );
   }
 
@@ -74,7 +86,10 @@ public function access($entity, AccountInterface $account = NULL, $return_as_obj
     if ($entity && $this->moderationInfo->isModeratedEntity($entity)) {
       $bundle_info = $this->bundleInfo->getBundleInfo($entity->getEntityTypeId());
       $bundle_label = $bundle_info[$entity->bundle()]['label'];
-      drupal_set_message($this->t("@bundle @label were skipped as they are under moderation and may not be directly unpublished.", ['@bundle' => $bundle_label, '@label' => $entity->getEntityType()->getPluralLabel()]), 'warning');
+      $this->messenger->addWarning($this->t("@bundle @label were skipped as they are under moderation and may not be directly unpublished.", [
+        '@bundle' => $bundle_label,
+        '@label' => $entity->getEntityType()->getPluralLabel(),
+      ]));
       $result = AccessResult::forbidden('Cannot directly unpublish moderated entities.');
       return $return_as_object ? $result : $result->isAllowed();
     }
diff --git a/core/modules/content_translation/content_translation.install b/core/modules/content_translation/content_translation.install
index 0e4727009217..93a996822114 100644
--- a/core/modules/content_translation/content_translation.install
+++ b/core/modules/content_translation/content_translation.install
@@ -23,14 +23,14 @@ function content_translation_install() {
       ':language_url' => Url::fromRoute('entity.configurable_language.collection')->toString()
     ];
     $message = t('This site has only a single language enabled. <a href=":language_url">Add at least one more language</a> in order to translate content.', $t_args);
-    drupal_set_message($message, 'warning');
+    \Drupal::messenger()->addWarning($message);
   }
   // Point the user to the content translation settings.
   $t_args = [
     ':settings_url' => Url::fromRoute('language.content_settings_page')->toString()
   ];
   $message = t('<a href=":settings_url">Enable translation</a> for <em>content types</em>, <em>taxonomy vocabularies</em>, <em>accounts</em>, or any other element you wish to translate.', $t_args);
-  drupal_set_message($message, 'warning');
+  \Drupal::messenger()->addWarning($message);
 }
 
 /**
diff --git a/core/modules/content_translation/src/ContentTranslationHandler.php b/core/modules/content_translation/src/ContentTranslationHandler.php
index e7855fb1efc5..a1ab3d5f8f67 100644
--- a/core/modules/content_translation/src/ContentTranslationHandler.php
+++ b/core/modules/content_translation/src/ContentTranslationHandler.php
@@ -734,7 +734,7 @@ public function entityFormSourceChange($form, FormStateInterface $form_state) {
       'target' => $form_object->getFormLangcode($form_state),
     ]);
     $languages = $this->languageManager->getLanguages();
-    drupal_set_message(t('Source language set to: %language', ['%language' => $languages[$source]->getName()]));
+    $this->messenger->addStatus(t('Source language set to: %language', ['%language' => $languages[$source]->getName()]));
   }
 
   /**
@@ -746,7 +746,7 @@ public function entityFormDelete($form, FormStateInterface $form_state) {
     $form_object = $form_state->getFormObject();
     $entity = $form_object->getEntity();
     if (count($entity->getTranslationLanguages()) > 1) {
-      drupal_set_message(t('This will delete all the translations of %label.', ['%label' => $entity->label()]), 'warning');
+      $this->messenger->addWarning(t('This will delete all the translations of %label.', ['%label' => $entity->label()]));
     }
   }
 
diff --git a/core/modules/dblog/src/Form/DblogClearLogConfirmForm.php b/core/modules/dblog/src/Form/DblogClearLogConfirmForm.php
index 46344eba0654..e567729b36a1 100644
--- a/core/modules/dblog/src/Form/DblogClearLogConfirmForm.php
+++ b/core/modules/dblog/src/Form/DblogClearLogConfirmForm.php
@@ -68,7 +68,7 @@ public function getCancelUrl() {
   public function submitForm(array &$form, FormStateInterface $form_state) {
     $_SESSION['dblog_overview_filter'] = [];
     $this->connection->truncate('watchdog')->execute();
-    drupal_set_message($this->t('Database log cleared.'));
+    $this->messenger()->addStatus($this->t('Database log cleared.'));
     $form_state->setRedirectUrl($this->getCancelUrl());
   }
 
diff --git a/core/modules/field/field.module b/core/modules/field/field.module
index 14340b8bf0a2..4d4d4822fa61 100644
--- a/core/modules/field/field.module
+++ b/core/modules/field/field.module
@@ -324,12 +324,12 @@ function field_form_config_admin_import_form_alter(&$form, FormStateInterface $f
       foreach ($field_storages as $field) {
         $field_labels[] = $field->label();
       }
-      drupal_set_message(\Drupal::translation()->formatPlural(
+      \Drupal::messenger()->addWarning(\Drupal::translation()->formatPlural(
         count($field_storages),
         'This synchronization will delete data from the field %fields.',
         'This synchronization will delete data from the fields: %fields.',
         ['%fields' => implode(', ', $field_labels)]
-      ), 'warning');
+      ));
     }
   }
 }
diff --git a/core/modules/field/tests/modules/field_test/field_test.module b/core/modules/field/tests/modules/field_test/field_test.module
index 1d7e2d6312d3..4458672f67ec 100644
--- a/core/modules/field/tests/modules/field_test/field_test.module
+++ b/core/modules/field/tests/modules/field_test/field_test.module
@@ -104,7 +104,8 @@ function field_test_field_widget_form_alter(&$element, FormStateInterface $form_
   // Set a message if this is for the form displayed to set default value for
   // the field.
   if ($context['default']) {
-    drupal_set_message('From hook_field_widget_form_alter(): Default form is true.');
+    \Drupal::messenger()
+      ->addStatus('From hook_field_widget_form_alter(): Default form is true.');
   }
 }
 
@@ -140,7 +141,7 @@ function _field_test_alter_widget($hook, array &$elements, FormStateInterface $f
   // Set a message if this is for the form displayed to set default value for
   // the field.
   if ($context['default']) {
-    drupal_set_message("From $hook(): Default form is true.");
+    \Drupal::messenger()->addStatus("From $hook(): Default form is true.");
   }
   $alter_info = \Drupal::state()->get("field_test.widget_alter_test");
   $name = $context['items']->getFieldDefinition()->getName();
diff --git a/core/modules/field/tests/modules/field_test/src/Form/NestedEntityTestForm.php b/core/modules/field/tests/modules/field_test/src/Form/NestedEntityTestForm.php
index ed99a05e9752..aed95dc929e8 100644
--- a/core/modules/field/tests/modules/field_test/src/Form/NestedEntityTestForm.php
+++ b/core/modules/field/tests/modules/field_test/src/Form/NestedEntityTestForm.php
@@ -92,7 +92,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) {
   }
 
   /**
-   * {@inheritdoc]
+   * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
     /** @var \Drupal\Core\Entity\EntityInterface $entity_1 */
@@ -103,7 +103,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     $entity_2 = $form_state->get('entity_2');
     $entity_2->save();
 
-    drupal_set_message($this->t('test_entities @id_1 and @id_2 have been updated.', ['@id_1' => $entity_1->id(), '@id_2' => $entity_2->id()]));
+    $this->messenger()->addStatus($this->t('test_entities @id_1 and @id_2 have been updated.', ['@id_1' => $entity_1->id(), '@id_2' => $entity_2->id()]));
   }
 
 }
diff --git a/core/modules/field_ui/src/Form/EntityDisplayFormBase.php b/core/modules/field_ui/src/Form/EntityDisplayFormBase.php
index 04b267cd2411..0df8e765dec5 100644
--- a/core/modules/field_ui/src/Form/EntityDisplayFormBase.php
+++ b/core/modules/field_ui/src/Form/EntityDisplayFormBase.php
@@ -147,7 +147,7 @@ public function form(array $form, FormStateInterface $form_state) {
     ];
 
     if (empty($field_definitions) && empty($extra_fields) && $route_info = FieldUI::getOverviewRouteInfo($this->entity->getTargetEntityTypeId(), $this->entity->getTargetBundle())) {
-      drupal_set_message($this->t('There are no fields yet added. You can add new fields on the <a href=":link">Manage fields</a> page.', [':link' => $route_info->toString()]), 'warning');
+      $this->messenger()->addWarning($this->t('There are no fields yet added. You can add new fields on the <a href=":link">Manage fields</a> page.', [':link' => $route_info->toString()]));
       return $form;
     }
 
@@ -545,7 +545,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
 
           $display_mode_label = $display_modes[$mode]['label'];
           $url = $this->getOverviewUrl($mode);
-          drupal_set_message($this->t('The %display_mode mode now uses custom display settings. You might want to <a href=":url">configure them</a>.', ['%display_mode' => $display_mode_label, ':url' => $url->toString()]));
+          $this->messenger()->addStatus($this->t('The %display_mode mode now uses custom display settings. You might want to <a href=":url">configure them</a>.', ['%display_mode' => $display_mode_label, ':url' => $url->toString()]));
         }
         $statuses[$mode] = !empty($value);
       }
@@ -553,7 +553,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $this->saveDisplayStatuses($statuses);
     }
 
-    drupal_set_message($this->t('Your settings have been saved.'));
+    $this->messenger()->addStatus($this->t('Your settings have been saved.'));
   }
 
   /**
diff --git a/core/modules/field_ui/src/Form/EntityDisplayModeFormBase.php b/core/modules/field_ui/src/Form/EntityDisplayModeFormBase.php
index 72a8a19643a0..0e502f71b71a 100644
--- a/core/modules/field_ui/src/Form/EntityDisplayModeFormBase.php
+++ b/core/modules/field_ui/src/Form/EntityDisplayModeFormBase.php
@@ -78,7 +78,7 @@ public function exists($entity_id, array $element) {
    * {@inheritdoc}
    */
   public function save(array $form, FormStateInterface $form_state) {
-    drupal_set_message($this->t('Saved the %label @entity-type.', ['%label' => $this->entity->label(), '@entity-type' => $this->entityType->getLowercaseLabel()]));
+    $this->messenger()->addStatus($this->t('Saved the %label @entity-type.', ['%label' => $this->entity->label(), '@entity-type' => $this->entityType->getLowercaseLabel()]));
     $this->entity->save();
     \Drupal::entityManager()->clearCachedFieldDefinitions();
     $form_state->setRedirectUrl($this->entity->urlInfo('collection'));
diff --git a/core/modules/field_ui/src/Form/FieldConfigDeleteForm.php b/core/modules/field_ui/src/Form/FieldConfigDeleteForm.php
index ab83e8fa3512..efdecbfbfc51 100644
--- a/core/modules/field_ui/src/Form/FieldConfigDeleteForm.php
+++ b/core/modules/field_ui/src/Form/FieldConfigDeleteForm.php
@@ -98,10 +98,10 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
 
     if ($field_storage && !$field_storage->isLocked()) {
       $this->entity->delete();
-      drupal_set_message($this->t('The field %field has been deleted from the %type content type.', ['%field' => $this->entity->label(), '%type' => $bundle_label]));
+      $this->messenger()->addStatus($this->t('The field %field has been deleted from the %type content type.', ['%field' => $this->entity->label(), '%type' => $bundle_label]));
     }
     else {
-      drupal_set_message($this->t('There was a problem removing the %field from the %type content type.', ['%field' => $this->entity->label(), '%type' => $bundle_label]), 'error');
+      $this->messenger()->addError($this->t('There was a problem removing the %field from the %type content type.', ['%field' => $this->entity->label(), '%type' => $bundle_label]));
     }
 
     $form_state->setRedirectUrl($this->getCancelUrl());
diff --git a/core/modules/field_ui/src/Form/FieldConfigEditForm.php b/core/modules/field_ui/src/Form/FieldConfigEditForm.php
index 34868add4796..bf19a4af2d54 100644
--- a/core/modules/field_ui/src/Form/FieldConfigEditForm.php
+++ b/core/modules/field_ui/src/Form/FieldConfigEditForm.php
@@ -177,7 +177,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
   public function save(array $form, FormStateInterface $form_state) {
     $this->entity->save();
 
-    drupal_set_message($this->t('Saved %label configuration.', ['%label' => $this->entity->getLabel()]));
+    $this->messenger()->addStatus($this->t('Saved %label configuration.', ['%label' => $this->entity->getLabel()]));
 
     $request = $this->getRequest();
     if (($destinations = $request->query->get('destinations')) && $next_destination = FieldUI::getNextDestination($destinations)) {
diff --git a/core/modules/field_ui/src/Form/FieldStorageAddForm.php b/core/modules/field_ui/src/Form/FieldStorageAddForm.php
index 584cc9684674..5afd358a6782 100644
--- a/core/modules/field_ui/src/Form/FieldStorageAddForm.php
+++ b/core/modules/field_ui/src/Form/FieldStorageAddForm.php
@@ -370,7 +370,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       }
       catch (\Exception $e) {
         $error = TRUE;
-        drupal_set_message($this->t('There was a problem creating field %label: @message', ['%label' => $values['label'], '@message' => $e->getMessage()]), 'error');
+        $this->messenger()->addError($this->t('There was a problem creating field %label: @message', ['%label' => $values['label'], '@message' => $e->getMessage()]));
       }
     }
 
@@ -401,7 +401,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       }
       catch (\Exception $e) {
         $error = TRUE;
-        drupal_set_message($this->t('There was a problem creating field %label: @message', ['%label' => $values['label'], '@message' => $e->getMessage()]), 'error');
+        $this->messenger()->addError($this->t('There was a problem creating field %label: @message', ['%label' => $values['label'], '@message' => $e->getMessage()]));
       }
     }
 
@@ -411,7 +411,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $form_state->setRedirectUrl(FieldUI::getNextDestination($destinations, $form_state));
     }
     elseif (!$error) {
-      drupal_set_message($this->t('Your settings have been saved.'));
+      $this->messenger()->addStatus($this->t('Your settings have been saved.'));
     }
   }
 
diff --git a/core/modules/field_ui/src/Form/FieldStorageConfigEditForm.php b/core/modules/field_ui/src/Form/FieldStorageConfigEditForm.php
index 0ae5084c0964..bce79d6af2eb 100644
--- a/core/modules/field_ui/src/Form/FieldStorageConfigEditForm.php
+++ b/core/modules/field_ui/src/Form/FieldStorageConfigEditForm.php
@@ -222,7 +222,7 @@ public function save(array $form, FormStateInterface $form_state) {
     $field_label = $form_state->get('field_config')->label();
     try {
       $this->entity->save();
-      drupal_set_message($this->t('Updated field %label field settings.', ['%label' => $field_label]));
+      $this->messenger()->addStatus($this->t('Updated field %label field settings.', ['%label' => $field_label]));
       $request = $this->getRequest();
       if (($destinations = $request->query->get('destinations')) && $next_destination = FieldUI::getNextDestination($destinations)) {
         $request->query->remove('destinations');
@@ -233,7 +233,7 @@ public function save(array $form, FormStateInterface $form_state) {
       }
     }
     catch (\Exception $e) {
-      drupal_set_message($this->t('Attempt to update field %label failed: %message.', ['%label' => $field_label, '%message' => $e->getMessage()]), 'error');
+      $this->messenger()->addStatus($this->t('Attempt to update field %label failed: %message.', ['%label' => $field_label, '%message' => $e->getMessage()]));
     }
   }
 
diff --git a/core/modules/file/file.module b/core/modules/file/file.module
index 8fd68231044d..c0003b350af3 100644
--- a/core/modules/file/file.module
+++ b/core/modules/file/file.module
@@ -8,6 +8,7 @@
 use Drupal\Core\Datetime\Entity\DateFormat;
 use Drupal\Core\Field\FieldDefinitionInterface;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Core\Render\BubbleableMetadata;
 use Drupal\Core\Render\Element;
 use Drupal\Core\Routing\RouteMatchInterface;
@@ -161,7 +162,7 @@ function file_copy(FileInterface $source, $destination = NULL, $replace = FILE_E
     else {
       \Drupal::logger('file')->notice('File %file could not be copied because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', ['%file' => $source->getFileUri(), '%destination' => $destination]);
     }
-    drupal_set_message(t('The specified file %file could not be copied because the destination is invalid. More information is available in the system log.', ['%file' => $source->getFileUri()]), 'error');
+    \Drupal::messenger()->addError(t('The specified file %file could not be copied because the destination is invalid. More information is available in the system log.', ['%file' => $source->getFileUri()]));
     return FALSE;
   }
 
@@ -236,7 +237,7 @@ function file_move(FileInterface $source, $destination = NULL, $replace = FILE_E
     else {
       \Drupal::logger('file')->notice('File %file could not be moved because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', ['%file' => $source->getFileUri(), '%destination' => $destination]);
     }
-    drupal_set_message(t('The specified file %file could not be moved because the destination is invalid. More information is available in the system log.', ['%file' => $source->getFileUri()]), 'error');
+    \Drupal::messenger()->addError(t('The specified file %file could not be moved because the destination is invalid. More information is available in the system log.', ['%file' => $source->getFileUri()]));
     return FALSE;
   }
 
@@ -484,7 +485,7 @@ function file_validate_image_resolution(FileInterface $file, $maximum_dimensions
                 '%new_height' => $image->getHeight(),
               ]);
           }
-          drupal_set_message($message);
+          \Drupal::messenger()->addStatus($message);
         }
         else {
           $errors[] = t('The image exceeds the maximum allowed dimensions and an attempt to resize it failed.');
@@ -552,7 +553,7 @@ function file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAM
   }
   if (!file_valid_uri($destination)) {
     \Drupal::logger('file')->notice('The data could not be saved because the destination %destination is invalid. This may be caused by improper use of file_save_data() or a missing stream wrapper.', ['%destination' => $destination]);
-    drupal_set_message(t('The data could not be saved because the destination is invalid. More information is available in the system log.'), 'error');
+    \Drupal::messenger()->addError(t('The data could not be saved because the destination is invalid. More information is available in the system log.'));
     return FALSE;
   }
 
@@ -766,7 +767,7 @@ function file_cron() {
 function _file_save_upload_from_form(array $element, FormStateInterface $form_state, $delta = NULL, $replace = FILE_EXISTS_RENAME) {
   // Get all errors set before calling this method. This will also clear them
   // from $_SESSION.
-  $errors_before = drupal_get_messages('error');
+  $errors_before = \Drupal::messenger()->deleteByType(MessengerInterface::TYPE_ERROR);
 
   $upload_location = isset($element['#upload_location']) ? $element['#upload_location'] : FALSE;
   $upload_name = implode('_', $element['#parents']);
@@ -776,9 +777,8 @@ function _file_save_upload_from_form(array $element, FormStateInterface $form_st
 
   // Get new errors that are generated while trying to save the upload. This
   // will also clear them from $_SESSION.
-  $errors_new = drupal_get_messages('error');
-  if (!empty($errors_new['error'])) {
-    $errors_new = $errors_new['error'];
+  $errors_new = \Drupal::messenger()->deleteByType(MessengerInterface::TYPE_ERROR);
+  if (!empty($errors_new)) {
 
     if (count($errors_new) > 1) {
       // Render multiple errors into a single message.
@@ -803,9 +803,9 @@ function _file_save_upload_from_form(array $element, FormStateInterface $form_st
 
   // Ensure that errors set prior to calling this method are still shown to the
   // user.
-  if (!empty($errors_before['error'])) {
-    foreach ($errors_before['error'] as $error) {
-      drupal_set_message($error, 'error');
+  if (!empty($errors_before)) {
+    foreach ($errors_before as $error) {
+      \Drupal::messenger()->addError($error);
     }
   }
 
@@ -893,13 +893,13 @@ function file_save_upload($form_field_name, $validators = [], $destination = FAL
     switch ($file_info->getError()) {
       case UPLOAD_ERR_INI_SIZE:
       case UPLOAD_ERR_FORM_SIZE:
-        drupal_set_message(t('The file %file could not be saved because it exceeds %maxsize, the maximum allowed size for uploads.', ['%file' => $file_info->getFilename(), '%maxsize' => format_size(file_upload_max_size())]), 'error');
+        \Drupal::messenger()->addError(t('The file %file could not be saved because it exceeds %maxsize, the maximum allowed size for uploads.', ['%file' => $file_info->getFilename(), '%maxsize' => format_size(file_upload_max_size())]));
         $files[$i] = FALSE;
         continue;
 
       case UPLOAD_ERR_PARTIAL:
       case UPLOAD_ERR_NO_FILE:
-        drupal_set_message(t('The file %file could not be saved because the upload did not complete.', ['%file' => $file_info->getFilename()]), 'error');
+        \Drupal::messenger()->addError(t('The file %file could not be saved because the upload did not complete.', ['%file' => $file_info->getFilename()]));
         $files[$i] = FALSE;
         continue;
 
@@ -912,7 +912,7 @@ function file_save_upload($form_field_name, $validators = [], $destination = FAL
 
         // Unknown error
       default:
-        drupal_set_message(t('The file %file could not be saved. An unknown error has occurred.', ['%file' => $file_info->getFilename()]), 'error');
+        \Drupal::messenger()->addError(t('The file %file could not be saved. An unknown error has occurred.', ['%file' => $file_info->getFilename()]));
         $files[$i] = FALSE;
         continue;
 
@@ -967,7 +967,7 @@ function file_save_upload($form_field_name, $validators = [], $destination = FAL
       // to add it here or else the file upload will fail.
       if (!empty($extensions)) {
         $validators['file_validate_extensions'][0] .= ' txt';
-        drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', ['%filename' => $file->getFilename()]));
+        \Drupal::messenger()->addStatus(t('For security reasons, your upload has been renamed to %filename.', ['%filename' => $file->getFilename()]));
       }
     }
 
@@ -979,7 +979,7 @@ function file_save_upload($form_field_name, $validators = [], $destination = FAL
     // Assert that the destination contains a valid stream.
     $destination_scheme = file_uri_scheme($destination);
     if (!file_stream_wrapper_valid_scheme($destination_scheme)) {
-      drupal_set_message(t('The file could not be uploaded because the destination %destination is invalid.', ['%destination' => $destination]), 'error');
+      \Drupal::messenger()->addError(t('The file could not be uploaded because the destination %destination is invalid.', ['%destination' => $destination]));
       $files[$i] = FALSE;
       continue;
     }
@@ -993,7 +993,7 @@ function file_save_upload($form_field_name, $validators = [], $destination = FAL
     // If file_destination() returns FALSE then $replace === FILE_EXISTS_ERROR and
     // there's an existing file so we need to bail.
     if ($file->destination === FALSE) {
-      drupal_set_message(t('The file %source could not be uploaded because a file by that name already exists in the destination %directory.', ['%source' => $form_field_name, '%directory' => $destination]), 'error');
+      \Drupal::messenger()->addError(t('The file %source could not be uploaded because a file by that name already exists in the destination %directory.', ['%source' => $form_field_name, '%directory' => $destination]));
       $files[$i] = FALSE;
       continue;
     }
@@ -1015,16 +1015,17 @@ function file_save_upload($form_field_name, $validators = [], $destination = FAL
           '#items' => $errors,
         ],
       ];
-      // @todo Add support for render arrays in drupal_set_message()? See
-      //  https://www.drupal.org/node/2505497.
-      drupal_set_message(\Drupal::service('renderer')->renderPlain($message), 'error');
+      // @todo Add support for render arrays in
+      // \Drupal\Core\Messenger\MessengerInterface::addMessage()?
+      // @see https://www.drupal.org/node/2505497.
+      \Drupal::messenger()->addError(\Drupal::service('renderer')->renderPlain($message));
       $files[$i] = FALSE;
       continue;
     }
 
     $file->setFileUri($file->destination);
     if (!drupal_move_uploaded_file($file_info->getRealPath(), $file->getFileUri())) {
-      drupal_set_message(t('File upload error. Could not move uploaded file.'), 'error');
+      \Drupal::messenger()->addError(t('File upload error. Could not move uploaded file.'));
       \Drupal::logger('file')->notice('Upload error. Could not move uploaded file %file to destination %destination.', ['%file' => $file->getFilename(), '%destination' => $file->getFileUri()]);
       $files[$i] = FALSE;
       continue;
diff --git a/core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php b/core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php
index 587a396fc602..f1da5a4b5f1f 100644
--- a/core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php
+++ b/core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php
@@ -365,7 +365,7 @@ public static function validateMultipleCount($element, FormStateInterface $form_
         '%list' => implode(', ', $removed_names),
       ];
       $message = t('Field %field can only hold @max values but there were @count uploaded. The following files have been omitted as a result: %list.', $args);
-      drupal_set_message($message, 'warning');
+      \Drupal::messenger()->addWarning($message);
       $values['fids'] = array_slice($values['fids'], 0, $keep);
       NestedArray::setValue($form_state->getValues(), $element['#parents'], $values);
     }
diff --git a/core/modules/file/tests/file_module_test/src/Form/FileModuleTestForm.php b/core/modules/file/tests/file_module_test/src/Form/FileModuleTestForm.php
index 51353f6381b1..78b6e7d05d41 100644
--- a/core/modules/file/tests/file_module_test/src/Form/FileModuleTestForm.php
+++ b/core/modules/file/tests/file_module_test/src/Form/FileModuleTestForm.php
@@ -85,7 +85,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $fids[] = $fid;
     }
 
-    drupal_set_message($this->t('The file ids are %fids.', ['%fids' => implode(',', $fids)]));
+    \Drupal::messenger()->addStatus($this->t('The file ids are %fids.', ['%fids' => implode(',', $fids)]));
   }
 
 }
diff --git a/core/modules/file/tests/file_test/src/Form/FileTestForm.php b/core/modules/file/tests/file_test/src/Form/FileTestForm.php
index f43e20a8e900..42a5dd9280ec 100644
--- a/core/modules/file/tests/file_test/src/Form/FileTestForm.php
+++ b/core/modules/file/tests/file_test/src/Form/FileTestForm.php
@@ -108,13 +108,13 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     $file = file_save_upload('file_test_upload', $validators, $destination, 0, $form_state->getValue('file_test_replace'));
     if ($file) {
       $form_state->setValue('file_test_upload', $file);
-      drupal_set_message(t('File @filepath was uploaded.', ['@filepath' => $file->getFileUri()]));
-      drupal_set_message(t('File name is @filename.', ['@filename' => $file->getFilename()]));
-      drupal_set_message(t('File MIME type is @mimetype.', ['@mimetype' => $file->getMimeType()]));
-      drupal_set_message(t('You WIN!'));
+      \Drupal::messenger()->addStatus(t('File @filepath was uploaded.', ['@filepath' => $file->getFileUri()]));
+      \Drupal::messenger()->addStatus(t('File name is @filename.', ['@filename' => $file->getFilename()]));
+      \Drupal::messenger()->addStatus(t('File MIME type is @mimetype.', ['@mimetype' => $file->getMimeType()]));
+      \Drupal::messenger()->addStatus(t('You WIN!'));
     }
     elseif ($file === FALSE) {
-      drupal_set_message(t('Epic upload FAIL!'), 'error');
+      \Drupal::messenger()->addError(t('Epic upload FAIL!'));
     }
   }
 
diff --git a/core/modules/filter/src/FilterFormatAddForm.php b/core/modules/filter/src/FilterFormatAddForm.php
index 39f1cb610b58..07a7d0a415b9 100644
--- a/core/modules/filter/src/FilterFormatAddForm.php
+++ b/core/modules/filter/src/FilterFormatAddForm.php
@@ -23,7 +23,7 @@ public function form(array $form, FormStateInterface $form_state) {
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
     parent::submitForm($form, $form_state);
-    drupal_set_message($this->t('Added text format %format.', ['%format' => $this->entity->label()]));
+    $this->messenger()->addStatus($this->t('Added text format %format.', ['%format' => $this->entity->label()]));
     return $this->entity;
   }
 
diff --git a/core/modules/filter/src/FilterFormatEditForm.php b/core/modules/filter/src/FilterFormatEditForm.php
index 8173a785c0a4..b8decc138fa1 100644
--- a/core/modules/filter/src/FilterFormatEditForm.php
+++ b/core/modules/filter/src/FilterFormatEditForm.php
@@ -31,7 +31,7 @@ public function form(array $form, FormStateInterface $form_state) {
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
     parent::submitForm($form, $form_state);
-    drupal_set_message($this->t('The text format %format has been updated.', ['%format' => $this->entity->label()]));
+    $this->messenger()->addStatus($this->t('The text format %format has been updated.', ['%format' => $this->entity->label()]));
     return $this->entity;
   }
 
diff --git a/core/modules/filter/src/FilterFormatFormBase.php b/core/modules/filter/src/FilterFormatFormBase.php
index cbcb632189b7..5526b02fd4fb 100644
--- a/core/modules/filter/src/FilterFormatFormBase.php
+++ b/core/modules/filter/src/FilterFormatFormBase.php
@@ -64,7 +64,7 @@ public function form(array $form, FormStateInterface $form_state) {
       // When a filter is missing, it is replaced by the null filter. Remove it
       // here, so that saving the form will remove the missing filter.
       if ($filter instanceof FilterNull) {
-        drupal_set_message($this->t('The %filter filter is missing, and will be removed once this format is saved.', ['%filter' => $filter_id]), 'warning');
+        $this->messenger()->addWarning($this->t('The %filter filter is missing, and will be removed once this format is saved.', ['%filter' => $filter_id]));
         $filters->removeInstanceID($filter_id);
       }
     }
diff --git a/core/modules/filter/src/FilterFormatListBuilder.php b/core/modules/filter/src/FilterFormatListBuilder.php
index cf084564c0b4..f15474694d5a 100644
--- a/core/modules/filter/src/FilterFormatListBuilder.php
+++ b/core/modules/filter/src/FilterFormatListBuilder.php
@@ -8,6 +8,7 @@
 use Drupal\Core\Entity\EntityStorageInterface;
 use Drupal\Core\Entity\EntityTypeInterface;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Symfony\Component\DependencyInjection\ContainerInterface;
 
 /**
@@ -29,6 +30,13 @@ class FilterFormatListBuilder extends DraggableListBuilder {
    */
   protected $configFactory;
 
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
   /**
    * Constructs a new FilterFormatListBuilder.
    *
@@ -38,11 +46,14 @@ class FilterFormatListBuilder extends DraggableListBuilder {
    *   The entity storage class.
    * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
    *   The config factory.
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   The messenger.
    */
-  public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, ConfigFactoryInterface $config_factory) {
+  public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, ConfigFactoryInterface $config_factory, MessengerInterface $messenger) {
     parent::__construct($entity_type, $storage);
 
     $this->configFactory = $config_factory;
+    $this->messenger = $messenger;
   }
 
   /**
@@ -52,7 +63,8 @@ public static function createInstance(ContainerInterface $container, EntityTypeI
     return new static(
       $entity_type,
       $container->get('entity.manager')->getStorage($entity_type->id()),
-      $container->get('config.factory')
+      $container->get('config.factory'),
+      $container->get('messenger')
     );
   }
 
@@ -150,7 +162,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     parent::submitForm($form, $form_state);
 
     filter_formats_reset();
-    drupal_set_message($this->t('The text format ordering has been saved.'));
+    $this->messenger->addStatus($this->t('The text format ordering has been saved.'));
   }
 
 }
diff --git a/core/modules/filter/src/Form/FilterDisableForm.php b/core/modules/filter/src/Form/FilterDisableForm.php
index a8a2ba3aad44..0c213a26666e 100644
--- a/core/modules/filter/src/Form/FilterDisableForm.php
+++ b/core/modules/filter/src/Form/FilterDisableForm.php
@@ -46,7 +46,7 @@ public function getDescription() {
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
     $this->entity->disable()->save();
-    drupal_set_message($this->t('Disabled text format %format.', ['%format' => $this->entity->label()]));
+    $this->messenger()->addStatus($this->t('Disabled text format %format.', ['%format' => $this->entity->label()]));
 
     $form_state->setRedirectUrl($this->getCancelUrl());
   }
diff --git a/core/modules/filter/tests/filter_test/filter_test.module b/core/modules/filter/tests/filter_test/filter_test.module
index e3983b4f328d..27fedcb7d5a3 100644
--- a/core/modules/filter/tests/filter_test/filter_test.module
+++ b/core/modules/filter/tests/filter_test/filter_test.module
@@ -9,19 +9,19 @@
  * Implements hook_filter_format_insert().
  */
 function filter_test_filter_format_insert($format) {
-  drupal_set_message('hook_filter_format_insert invoked.');
+  \Drupal::messenger()->addStatus('hook_filter_format_insert invoked.');
 }
 
 /**
  * Implements hook_filter_format_update().
  */
 function filter_test_filter_format_update($format) {
-  drupal_set_message('hook_filter_format_update invoked.');
+  \Drupal::messenger()->addStatus('hook_filter_format_update invoked.');
 }
 
 /**
  * Implements hook_filter_format_disable().
  */
 function filter_test_filter_format_disable($format) {
-  drupal_set_message('hook_filter_format_disable invoked.');
+  \Drupal::messenger()->addStatus('hook_filter_format_disable invoked.');
 }
diff --git a/core/modules/forum/src/Form/DeleteForm.php b/core/modules/forum/src/Form/DeleteForm.php
index c65241019ab5..4cf56c328329 100644
--- a/core/modules/forum/src/Form/DeleteForm.php
+++ b/core/modules/forum/src/Form/DeleteForm.php
@@ -63,7 +63,7 @@ public function buildForm(array $form, FormStateInterface $form_state, TermInter
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
     $this->taxonomyTerm->delete();
-    drupal_set_message($this->t('The forum %label and all sub-forums have been deleted.', ['%label' => $this->taxonomyTerm->label()]));
+    $this->messenger()->addStatus($this->t('The forum %label and all sub-forums have been deleted.', ['%label' => $this->taxonomyTerm->label()]));
     $this->logger('forum')->notice('forum: deleted %label and all its sub-forums.', ['%label' => $this->taxonomyTerm->label()]);
     $form_state->setRedirectUrl($this->getCancelUrl());
   }
diff --git a/core/modules/forum/src/Form/ForumForm.php b/core/modules/forum/src/Form/ForumForm.php
index c894d3fbb300..28030cb9f75c 100644
--- a/core/modules/forum/src/Form/ForumForm.php
+++ b/core/modules/forum/src/Form/ForumForm.php
@@ -82,13 +82,13 @@ public function save(array $form, FormStateInterface $form_state) {
     $view_link = $term->link($term->getName());
     switch ($status) {
       case SAVED_NEW:
-        drupal_set_message($this->t('Created new @type %term.', ['%term' => $view_link, '@type' => $this->forumFormType]));
+        $this->messenger()->addStatus($this->t('Created new @type %term.', ['%term' => $view_link, '@type' => $this->forumFormType]));
         $this->logger('forum')->notice('Created new @type %term.', ['%term' => $term->getName(), '@type' => $this->forumFormType, 'link' => $link]);
         $form_state->setValue('tid', $term->id());
         break;
 
       case SAVED_UPDATED:
-        drupal_set_message($this->t('The @type %term has been updated.', ['%term' => $term->getName(), '@type' => $this->forumFormType]));
+        $this->messenger()->addStatus($this->t('The @type %term has been updated.', ['%term' => $term->getName(), '@type' => $this->forumFormType]));
         $this->logger('forum')->notice('Updated @type %term.', ['%term' => $term->getName(), '@type' => $this->forumFormType, 'link' => $link]);
         break;
     }
diff --git a/core/modules/help/src/Controller/HelpController.php b/core/modules/help/src/Controller/HelpController.php
index 74d46ecb0563..758d05dc6b82 100644
--- a/core/modules/help/src/Controller/HelpController.php
+++ b/core/modules/help/src/Controller/HelpController.php
@@ -119,7 +119,7 @@ public function helpPage($name) {
 
       $info = system_get_info('module', $name);
       if ($info['package'] === 'Core (Experimental)') {
-        drupal_set_message($this->t('This module is experimental. <a href=":url">Experimental modules</a> are provided for testing purposes only. Use at your own risk.', [':url' => 'https://www.drupal.org/core/experimental']), 'warning');
+        $this->messenger()->addWarning($this->t('This module is experimental. <a href=":url">Experimental modules</a> are provided for testing purposes only. Use at your own risk.', [':url' => 'https://www.drupal.org/core/experimental']));
       }
 
       $temp = $this->moduleHandler()->invoke($name, 'help', ["help.page.$name", $this->routeMatch]);
diff --git a/core/modules/image/src/Form/ImageEffectDeleteForm.php b/core/modules/image/src/Form/ImageEffectDeleteForm.php
index e45f7a562f8f..ae167fa6ab41 100644
--- a/core/modules/image/src/Form/ImageEffectDeleteForm.php
+++ b/core/modules/image/src/Form/ImageEffectDeleteForm.php
@@ -70,7 +70,7 @@ public function buildForm(array $form, FormStateInterface $form_state, ImageStyl
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
     $this->imageStyle->deleteImageEffect($this->imageEffect);
-    drupal_set_message($this->t('The image effect %name has been deleted.', ['%name' => $this->imageEffect->label()]));
+    $this->messenger()->addStatus($this->t('The image effect %name has been deleted.', ['%name' => $this->imageEffect->label()]));
     $form_state->setRedirectUrl($this->imageStyle->urlInfo('edit-form'));
   }
 
diff --git a/core/modules/image/src/Form/ImageEffectFormBase.php b/core/modules/image/src/Form/ImageEffectFormBase.php
index 74368d6082b4..d62baba4a080 100644
--- a/core/modules/image/src/Form/ImageEffectFormBase.php
+++ b/core/modules/image/src/Form/ImageEffectFormBase.php
@@ -123,7 +123,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     }
     $this->imageStyle->save();
 
-    drupal_set_message($this->t('The image effect was successfully applied.'));
+    $this->messenger()->addStatus($this->t('The image effect was successfully applied.'));
     $form_state->setRedirectUrl($this->imageStyle->urlInfo('edit-form'));
   }
 
diff --git a/core/modules/image/src/Form/ImageStyleAddForm.php b/core/modules/image/src/Form/ImageStyleAddForm.php
index e0f5654a5d8a..a1b3d9588ddc 100644
--- a/core/modules/image/src/Form/ImageStyleAddForm.php
+++ b/core/modules/image/src/Form/ImageStyleAddForm.php
@@ -16,7 +16,7 @@ class ImageStyleAddForm extends ImageStyleFormBase {
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
     parent::submitForm($form, $form_state);
-    drupal_set_message($this->t('Style %name was created.', ['%name' => $this->entity->label()]));
+    $this->messenger()->addStatus($this->t('Style %name was created.', ['%name' => $this->entity->label()]));
   }
 
   /**
diff --git a/core/modules/image/src/Form/ImageStyleEditForm.php b/core/modules/image/src/Form/ImageStyleEditForm.php
index e7cfd50c586c..6bf8dd9013a6 100644
--- a/core/modules/image/src/Form/ImageStyleEditForm.php
+++ b/core/modules/image/src/Form/ImageStyleEditForm.php
@@ -231,7 +231,7 @@ public function effectSave($form, FormStateInterface $form_state) {
       $effect_id = $this->entity->addImageEffect($effect);
       $this->entity->save();
       if (!empty($effect_id)) {
-        drupal_set_message($this->t('The image effect was successfully applied.'));
+        $this->messenger()->addStatus($this->t('The image effect was successfully applied.'));
       }
     }
   }
@@ -254,7 +254,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
    */
   public function save(array $form, FormStateInterface $form_state) {
     parent::save($form, $form_state);
-    drupal_set_message($this->t('Changes to the style have been saved.'));
+    $this->messenger()->addStatus($this->t('Changes to the style have been saved.'));
   }
 
   /**
diff --git a/core/modules/image/src/Form/ImageStyleFlushForm.php b/core/modules/image/src/Form/ImageStyleFlushForm.php
index df1d24e9ada4..f07213fb6049 100644
--- a/core/modules/image/src/Form/ImageStyleFlushForm.php
+++ b/core/modules/image/src/Form/ImageStyleFlushForm.php
@@ -45,7 +45,7 @@ public function getCancelUrl() {
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
     $this->entity->flush();
-    drupal_set_message($this->t('The image style %name has been flushed.', ['%name' => $this->entity->label()]));
+    $this->messenger()->addStatus($this->t('The image style %name has been flushed.', ['%name' => $this->entity->label()]));
     $form_state->setRedirectUrl($this->getCancelUrl());
   }
 
diff --git a/core/modules/inline_form_errors/src/FormErrorHandler.php b/core/modules/inline_form_errors/src/FormErrorHandler.php
index 2bcbfc60be7f..fda5fa136a2d 100644
--- a/core/modules/inline_form_errors/src/FormErrorHandler.php
+++ b/core/modules/inline_form_errors/src/FormErrorHandler.php
@@ -5,6 +5,7 @@
 use Drupal\Core\Form\FormElementHelper;
 use Drupal\Core\Form\FormErrorHandler as CoreFormErrorHandler;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Core\Render\Element;
 use Drupal\Core\Routing\LinkGeneratorTrait;
 use Drupal\Core\Render\RendererInterface;
@@ -28,6 +29,13 @@ class FormErrorHandler extends CoreFormErrorHandler {
    */
   protected $renderer;
 
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
   /**
    * Constructs a new FormErrorHandler.
    *
@@ -37,11 +45,14 @@ class FormErrorHandler extends CoreFormErrorHandler {
    *   The link generation service.
    * @param \Drupal\Core\Render\RendererInterface $renderer
    *   The renderer service.
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   The messenger.
    */
-  public function __construct(TranslationInterface $string_translation, LinkGeneratorInterface $link_generator, RendererInterface $renderer) {
+  public function __construct(TranslationInterface $string_translation, LinkGeneratorInterface $link_generator, RendererInterface $renderer, MessengerInterface $messenger) {
     $this->stringTranslation = $string_translation;
     $this->linkGenerator = $link_generator;
     $this->renderer = $renderer;
+    $this->messenger = $messenger;
   }
 
   /**
@@ -96,7 +107,7 @@ protected function displayErrorMessages(array $form, FormStateInterface $form_st
 
     // Set normal error messages for all remaining errors.
     foreach ($errors as $error) {
-      $this->drupalSetMessage($error, 'error');
+      $this->messenger->addError($error);
     }
 
     if (!empty($error_links)) {
@@ -111,7 +122,7 @@ protected function displayErrorMessages(array $form, FormStateInterface $form_st
         ],
       ];
       $message = $this->renderer->renderPlain($render_array);
-      $this->drupalSetMessage($message, 'error');
+      $this->messenger->addError($message);
     }
   }
 
diff --git a/core/modules/inline_form_errors/src/InlineFormErrorsServiceProvider.php b/core/modules/inline_form_errors/src/InlineFormErrorsServiceProvider.php
index 6b0cb14c37fe..62afbf0dc07f 100644
--- a/core/modules/inline_form_errors/src/InlineFormErrorsServiceProvider.php
+++ b/core/modules/inline_form_errors/src/InlineFormErrorsServiceProvider.php
@@ -17,7 +17,12 @@ class InlineFormErrorsServiceProvider extends ServiceProviderBase {
   public function alter(ContainerBuilder $container) {
     $container->getDefinition('form_error_handler')
       ->setClass(FormErrorHandler::class)
-      ->setArguments([new Reference('string_translation'), new Reference('link_generator'), new Reference('renderer')]);
+      ->setArguments([
+        new Reference('string_translation'),
+        new Reference('link_generator'),
+        new Reference('renderer'),
+        new Reference('messenger'),
+      ]);
   }
 
 }
diff --git a/core/modules/inline_form_errors/tests/src/Unit/FormErrorHandlerTest.php b/core/modules/inline_form_errors/tests/src/Unit/FormErrorHandlerTest.php
index f110b36af959..fccf9b6f11a0 100644
--- a/core/modules/inline_form_errors/tests/src/Unit/FormErrorHandlerTest.php
+++ b/core/modules/inline_form_errors/tests/src/Unit/FormErrorHandlerTest.php
@@ -3,6 +3,7 @@
 namespace Drupal\Tests\inline_form_errors\Unit;
 
 use Drupal\Core\Form\FormState;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Core\Render\RendererInterface;
 use Drupal\Core\Utility\LinkGeneratorInterface;
 use Drupal\inline_form_errors\FormErrorHandler;
@@ -14,35 +15,70 @@
  */
 class FormErrorHandlerTest extends UnitTestCase {
 
+  /**
+   * The form error handler.
+   *
+   * @var \Drupal\inline_form_errors\FormErrorHandler
+   */
+  protected $formErrorHandler;
+
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface|\PHPUnit_Framework_MockObject_MockObject
+   */
+  protected $messenger;
+
+  /**
+   * The renderer.
+   *
+   * @var \Drupal\Core\Render\RendererInterface|\PHPUnit_Framework_MockObject_MockObject
+   */
+  protected $renderer;
+
+  /**
+   * The link generator.
+   *
+   * @var \Drupal\Core\Utility\LinkGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
+   */
+  protected $linkGenerator;
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function setUp() {
+    parent::setUp();
+    $this->linkGenerator = $this->createMock(LinkGeneratorInterface::class);
+    $this->renderer = $this->createMock(RendererInterface::class);
+    $this->messenger = $this->createMock(MessengerInterface::class);
+
+    $this->formErrorHandler = new FormErrorHandler($this->getStringTranslationStub(), $this->linkGenerator, $this->renderer, $this->messenger);
+  }
+
   /**
    * @covers ::handleFormErrors
    * @covers ::displayErrorMessages
    */
   public function testDisplayErrorMessagesInline() {
-    $link_generator = $this->getMock(LinkGeneratorInterface::class);
-    $link_generator->expects($this->any())
+
+    $this->linkGenerator->expects($this->any())
       ->method('generate')
       ->willReturnArgument(0);
-    $renderer = $this->getMock(RendererInterface::class);
-    $form_error_handler = $this->getMockBuilder(FormErrorHandler::class)
-      ->setConstructorArgs([$this->getStringTranslationStub(), $link_generator, $renderer])
-      ->setMethods(['drupalSetMessage'])
-      ->getMock();
-
-    $form_error_handler->expects($this->at(0))
-      ->method('drupalSetMessage')
-      ->with('no title given', 'error');
-    $form_error_handler->expects($this->at(1))
-      ->method('drupalSetMessage')
-      ->with('element is invisible', 'error');
-    $form_error_handler->expects($this->at(2))
-      ->method('drupalSetMessage')
-      ->with('this missing element is invalid', 'error');
-    $form_error_handler->expects($this->at(3))
-      ->method('drupalSetMessage')
-      ->with('3 errors have been found: <ul-comma-list-mock><li-mock>Test 1</li-mock><li-mock>Test 2 &amp; a half</li-mock><li-mock>Test 3</li-mock></ul-comma-list-mock>', 'error');
-
-    $renderer->expects($this->any())
+
+    $this->messenger->expects($this->at(0))
+      ->method('addError')
+      ->with('no title given');
+    $this->messenger->expects($this->at(1))
+      ->method('addError')
+      ->with('element is invisible');
+    $this->messenger->expects($this->at(2))
+      ->method('addError')
+      ->with('this missing element is invalid');
+    $this->messenger->expects($this->at(3))
+      ->method('addError')
+      ->with('3 errors have been found: <ul-comma-list-mock><li-mock>Test 1</li-mock><li-mock>Test 2 &amp; a half</li-mock><li-mock>Test 3</li-mock></ul-comma-list-mock>');
+
+    $this->renderer->expects($this->any())
       ->method('renderPlain')
       ->will($this->returnCallback(function ($render_array) {
         return $render_array[0]['#markup'] . '<ul-comma-list-mock><li-mock>' . implode(array_map('htmlspecialchars', $render_array[1]['#items']), '</li-mock><li-mock>') . '</li-mock></ul-comma-list-mock>';
@@ -107,7 +143,7 @@ public function testDisplayErrorMessagesInline() {
     $form_state->setErrorByName('test5', 'no title given');
     $form_state->setErrorByName('test6', 'element is invisible');
     $form_state->setErrorByName('missing_element', 'this missing element is invalid');
-    $form_error_handler->handleFormErrors($form, $form_state);
+    $this->formErrorHandler->handleFormErrors($form, $form_state);
     $this->assertSame('invalid', $form['test1']['#errors']);
   }
 
@@ -116,11 +152,6 @@ public function testDisplayErrorMessagesInline() {
    * @covers ::setElementErrorsFromFormState
    */
   public function testSetElementErrorsFromFormState() {
-    $form_error_handler = $this->getMockBuilder(FormErrorHandler::class)
-      ->setConstructorArgs([$this->getStringTranslationStub(), $this->getMock(LinkGeneratorInterface::class), $this->getMock(RendererInterface::class)])
-      ->setMethods(['drupalSetMessage'])
-      ->getMock();
-
     $form = [
       '#parents' => [],
       '#form_id' => 'test_form',
@@ -135,7 +166,7 @@ public function testSetElementErrorsFromFormState() {
     ];
     $form_state = new FormState();
     $form_state->setErrorByName('test', 'invalid');
-    $form_error_handler->handleFormErrors($form, $form_state);
+    $this->formErrorHandler->handleFormErrors($form, $form_state);
     $this->assertSame('invalid', $form['test']['#errors']);
   }
 
@@ -143,14 +174,10 @@ public function testSetElementErrorsFromFormState() {
    * Tests that opting out of Inline Form Errors works.
    */
   public function testDisplayErrorMessagesNotInline() {
-    $form_error_handler = $this->getMockBuilder(FormErrorHandler::class)
-      ->setConstructorArgs([$this->getStringTranslationStub(), $this->getMock(LinkGeneratorInterface::class), $this->getMock(RendererInterface::class)])
-      ->setMethods(['drupalSetMessage'])
-      ->getMock();
 
-    $form_error_handler->expects($this->at(0))
-      ->method('drupalSetMessage')
-      ->with('invalid', 'error');
+    $this->messenger->expects($this->at(0))
+      ->method('addMessage')
+      ->with('invalid', 'error', FALSE);
 
     $form = [
       '#parents' => [],
@@ -166,7 +193,7 @@ public function testDisplayErrorMessagesNotInline() {
     ];
     $form_state = new FormState();
     $form_state->setErrorByName('test', 'invalid');
-    $form_error_handler->handleFormErrors($form, $form_state);
+    $this->formErrorHandler->handleFormErrors($form, $form_state);
   }
 
 }
diff --git a/core/modules/language/src/Form/ContentLanguageSettingsForm.php b/core/modules/language/src/Form/ContentLanguageSettingsForm.php
index 619d9440a3c5..5868d48faa22 100644
--- a/core/modules/language/src/Form/ContentLanguageSettingsForm.php
+++ b/core/modules/language/src/Form/ContentLanguageSettingsForm.php
@@ -157,7 +157,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
           ->save();
       }
     }
-    drupal_set_message($this->t('Settings successfully updated.'));
+    $this->messenger()->addStatus($this->t('Settings successfully updated.'));
   }
 
 }
diff --git a/core/modules/language/src/Form/LanguageAddForm.php b/core/modules/language/src/Form/LanguageAddForm.php
index 12484079ecd8..c0ef22b22d8a 100644
--- a/core/modules/language/src/Form/LanguageAddForm.php
+++ b/core/modules/language/src/Form/LanguageAddForm.php
@@ -88,12 +88,12 @@ public function save(array $form, FormStateInterface $form_state) {
 
     $t_args = ['%language' => $this->entity->label(), '%langcode' => $this->entity->id()];
     $this->logger('language')->notice('The %language (%langcode) language has been created.', $t_args);
-    drupal_set_message($this->t('The language %language has been created and can now be used.', $t_args));
+    $this->messenger()->addStatus($this->t('The language %language has been created and can now be used.', $t_args));
 
     if ($this->moduleHandler->moduleExists('block')) {
       // Tell the user they have the option to add a language switcher block
       // to their theme so they can switch between the languages.
-      drupal_set_message($this->t('Use one of the language switcher blocks to allow site visitors to switch between languages. You can enable these blocks on the <a href=":block-admin">block administration page</a>.', [':block-admin' => $this->url('block.admin_display')]));
+      $this->messenger()->addStatus($this->t('Use one of the language switcher blocks to allow site visitors to switch between languages. You can enable these blocks on the <a href=":block-admin">block administration page</a>.', [':block-admin' => $this->url('block.admin_display')]));
     }
     $form_state->setRedirectUrl($this->entity->urlInfo('collection'));
   }
diff --git a/core/modules/language/src/Form/NegotiationBrowserDeleteForm.php b/core/modules/language/src/Form/NegotiationBrowserDeleteForm.php
index 629fd086911a..1c7cdcbc28f6 100644
--- a/core/modules/language/src/Form/NegotiationBrowserDeleteForm.php
+++ b/core/modules/language/src/Form/NegotiationBrowserDeleteForm.php
@@ -76,7 +76,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
 
     $this->logger('language')->notice('The browser language detection mapping for the %browser browser language code has been deleted.', $args);
 
-    drupal_set_message($this->t('The mapping for the %browser browser language code has been deleted.', $args));
+    $this->messenger()->addStatus($this->t('The mapping for the %browser browser language code has been deleted.', $args));
 
     $form_state->setRedirect('language.negotiation_browser');
   }
diff --git a/core/modules/language/src/Form/NegotiationConfigureForm.php b/core/modules/language/src/Form/NegotiationConfigureForm.php
index 325a4351b01d..806123f45919 100644
--- a/core/modules/language/src/Form/NegotiationConfigureForm.php
+++ b/core/modules/language/src/Form/NegotiationConfigureForm.php
@@ -204,7 +204,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     $this->blockManager->clearCachedDefinitions();
 
     $form_state->setRedirect('language.negotiation');
-    drupal_set_message($this->t('Language detection configuration saved.'));
+    $this->messenger()->addStatus($this->t('Language detection configuration saved.'));
   }
 
   /**
diff --git a/core/modules/language/src/LanguageListBuilder.php b/core/modules/language/src/LanguageListBuilder.php
index 8d1515220434..21ef6ff5977a 100644
--- a/core/modules/language/src/LanguageListBuilder.php
+++ b/core/modules/language/src/LanguageListBuilder.php
@@ -9,6 +9,7 @@
 use Drupal\Core\Entity\EntityTypeInterface;
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\Core\Language\LanguageManagerInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Symfony\Component\DependencyInjection\ContainerInterface;
 
 /**
@@ -37,6 +38,13 @@ class LanguageListBuilder extends DraggableListBuilder {
    */
   protected $configFactory;
 
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
   /**
    * {@inheritdoc}
    */
@@ -45,7 +53,8 @@ public static function createInstance(ContainerInterface $container, EntityTypeI
       $entity_type,
       $container->get('entity.manager')->getStorage($entity_type->id()),
       $container->get('language_manager'),
-      $container->get('config.factory')
+      $container->get('config.factory'),
+      $container->get('messenger')
     );
   }
 
@@ -60,11 +69,14 @@ public static function createInstance(ContainerInterface $container, EntityTypeI
    *   The language manager.
    * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
    *   The factory for configuration objects.
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   The messenger.
    */
-  public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, LanguageManagerInterface $language_manager, ConfigFactoryInterface $config_factory) {
+  public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, LanguageManagerInterface $language_manager, ConfigFactoryInterface $config_factory, MessengerInterface $messenger) {
     parent::__construct($entity_type, $storage);
     $this->languageManager = $language_manager;
     $this->configFactory = $config_factory;
+    $this->messenger = $messenger;
   }
 
   /**
@@ -154,7 +166,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $this->languageManager->updateLockedLanguageWeights();
     }
 
-    drupal_set_message(t('Configuration saved.'));
+    $this->messenger->addStatus($this->t('Configuration saved.'));
     // Force the redirection to the page with the language we have just
     // selected as default.
     $form_state->setRedirectUrl($this->entities[$new_id]->urlInfo('collection', ['language' => $this->entities[$new_id]]));
diff --git a/core/modules/language/tests/language_test/language_test.module b/core/modules/language/tests/language_test/language_test.module
index 5ea9c360bd46..575b8e067a46 100644
--- a/core/modules/language/tests/language_test/language_test.module
+++ b/core/modules/language/tests/language_test/language_test.module
@@ -15,7 +15,7 @@
 function language_test_page_top() {
   if (\Drupal::moduleHandler()->moduleExists('language')) {
     language_test_store_language_negotiation();
-    drupal_set_message(t('Language negotiation method: @name', ['@name' => \Drupal::languageManager()->getNegotiatedLanguageMethod()]));
+    \Drupal::messenger()->addStatus(t('Language negotiation method: @name', ['@name' => \Drupal::languageManager()->getNegotiatedLanguageMethod()]));
   }
 }
 
diff --git a/core/modules/locale/locale.batch.inc b/core/modules/locale/locale.batch.inc
index b509c2542b55..c9cfdd5cb03d 100644
--- a/core/modules/locale/locale.batch.inc
+++ b/core/modules/locale/locale.batch.inc
@@ -104,22 +104,22 @@ function locale_translation_batch_status_finished($success, $results) {
       else {
         $message = \Drupal::translation()->formatPlural(count($results['failed_files']), 'One translation files could not be checked. See the log for details.', '@count translation files could not be checked. See the log for details.');
       }
-      drupal_set_message($message, 'error');
+      \Drupal::messenger()->addError($message);
     }
     if (isset($results['files'])) {
-      drupal_set_message(\Drupal::translation()->formatPlural(
+      \Drupal::messenger()->addStatus(\Drupal::translation()->formatPlural(
         count($results['files']),
         'Checked available interface translation updates for one project.',
         'Checked available interface translation updates for @count projects.'
       ));
     }
     if (!isset($results['failed_files']) && !isset($results['files'])) {
-      drupal_set_message(t('Nothing to check.'));
+      \Drupal::messenger()->addStatus(t('Nothing to check.'));
     }
     \Drupal::state()->set('locale.translation_last_checked', REQUEST_TIME);
   }
   else {
-    drupal_set_message(t('An error occurred trying to check available interface translation updates.'), 'error');
+    \Drupal::messenger()->addError(t('An error occurred trying to check available interface translation updates.'));
   }
 }
 
diff --git a/core/modules/locale/locale.bulk.inc b/core/modules/locale/locale.bulk.inc
index 6beb3fe35e1b..69b465b4ae19 100644
--- a/core/modules/locale/locale.bulk.inc
+++ b/core/modules/locale/locale.bulk.inc
@@ -372,7 +372,7 @@ function locale_translate_batch_finished($success, array $results) {
       else {
         $message = \Drupal::translation()->formatPlural(count($results['failed_files']), 'One translation file could not be imported. See the log for details.', '@count translation files could not be imported. See the log for details.');
       }
-      drupal_set_message($message, 'error');
+      \Drupal::messenger()->addError($message);
     }
     if (isset($results['files'])) {
       $skipped_files = [];
@@ -389,7 +389,7 @@ function locale_translate_batch_finished($success, array $results) {
           }
         }
       }
-      drupal_set_message(\Drupal::translation()->formatPlural(count($results['files']),
+      \Drupal::messenger()->addStatus(\Drupal::translation()->formatPlural(count($results['files']),
         'One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.',
         '@count translation files imported. %number translations were added, %update translations were updated and %delete translations were removed.',
         ['%number' => $additions, '%update' => $updates, '%delete' => $deletes]
@@ -403,7 +403,7 @@ function locale_translate_batch_finished($success, array $results) {
         else {
           $message = \Drupal::translation()->formatPlural($skips, 'One translation string was skipped because of disallowed or malformed HTML. See the log for details.', '@count translation strings were skipped because of disallowed or malformed HTML. See the log for details.');
         }
-        drupal_set_message($message, 'warning');
+        \Drupal::messenger()->addWarning($message);
         $logger->warning('@count disallowed HTML string(s) in files: @files.', ['@count' => $skips, '@files' => implode(',', $skipped_files)]);
       }
     }
@@ -630,11 +630,11 @@ function locale_config_batch_finished($success, array $results) {
   if ($success) {
     $configuration = isset($results['stats']['config']) ? $results['stats']['config'] : 0;
     if ($configuration) {
-      drupal_set_message(t('The configuration was successfully updated. There are %number configuration objects updated.', ['%number' => $configuration]));
+      \Drupal::messenger()->addStatus(t('The configuration was successfully updated. There are %number configuration objects updated.', ['%number' => $configuration]));
       \Drupal::logger('locale')->notice('The configuration was successfully updated. %number configuration objects updated.', ['%number' => $configuration]);
     }
     else {
-      drupal_set_message(t('No configuration objects have been updated.'));
+      \Drupal::messenger()->addStatus(t('No configuration objects have been updated.'));
       \Drupal::logger('locale')->warning('No configuration objects have been updated.');
     }
   }
diff --git a/core/modules/locale/src/Form/ExportForm.php b/core/modules/locale/src/Form/ExportForm.php
index 89f3fbb69dbe..af3282add077 100644
--- a/core/modules/locale/src/Form/ExportForm.php
+++ b/core/modules/locale/src/Form/ExportForm.php
@@ -180,7 +180,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $form_state->setResponse($response);
     }
     else {
-      drupal_set_message($this->t('Nothing to export.'));
+      $this->messenger()->addStatus($this->t('Nothing to export.'));
     }
   }
 
diff --git a/core/modules/locale/src/Form/ImportForm.php b/core/modules/locale/src/Form/ImportForm.php
index a9f15f07f18d..708a121de69a 100644
--- a/core/modules/locale/src/Form/ImportForm.php
+++ b/core/modules/locale/src/Form/ImportForm.php
@@ -175,7 +175,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     if (empty($language)) {
       $language = ConfigurableLanguage::createFromLangcode($form_state->getValue('langcode'));
       $language->save();
-      drupal_set_message($this->t('The language %language has been created.', ['%language' => $this->t($language->label())]));
+      $this->messenger()->addStatus($this->t('The language %language has been created.', ['%language' => $this->t($language->label())]));
     }
     $options = array_merge(_locale_translation_default_update_options(), [
       'langcode' => $form_state->getValue('langcode'),
diff --git a/core/modules/locale/src/Form/TranslateEditForm.php b/core/modules/locale/src/Form/TranslateEditForm.php
index 79656f2ed8e9..659d2964cc66 100644
--- a/core/modules/locale/src/Form/TranslateEditForm.php
+++ b/core/modules/locale/src/Form/TranslateEditForm.php
@@ -219,7 +219,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       }
     }
 
-    drupal_set_message($this->t('The strings have been saved.'));
+    $this->messenger()->addStatus($this->t('The strings have been saved.'));
 
     // Keep the user on the current pager page.
     $page = $this->getRequest()->query->get('page');
diff --git a/core/modules/media/src/Form/MediaDeleteMultipleConfirmForm.php b/core/modules/media/src/Form/MediaDeleteMultipleConfirmForm.php
index 2d6850b75331..6437753cd2c2 100644
--- a/core/modules/media/src/Form/MediaDeleteMultipleConfirmForm.php
+++ b/core/modules/media/src/Form/MediaDeleteMultipleConfirmForm.php
@@ -202,7 +202,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       }
 
       if ($total_count) {
-        drupal_set_message($this->formatPlural($total_count, 'Deleted 1 media item.', 'Deleted @count media items.'));
+        $this->messenger()->addStatus($this->formatPlural($total_count, 'Deleted 1 media item.', 'Deleted @count media items.'));
       }
 
       $this->tempStoreFactory->get('media_multiple_delete_confirm')->delete(\Drupal::currentUser()->id());
diff --git a/core/modules/media/src/MediaForm.php b/core/modules/media/src/MediaForm.php
index dd6b3fd2ad8b..6f860e23cdc0 100644
--- a/core/modules/media/src/MediaForm.php
+++ b/core/modules/media/src/MediaForm.php
@@ -65,11 +65,11 @@ public function save(array $form, FormStateInterface $form_state) {
 
     if ($saved === SAVED_NEW) {
       $logger->notice('@type: added %label.', $context);
-      drupal_set_message($this->t('@type %label has been created.', $t_args));
+      $this->messenger()->addStatus($this->t('@type %label has been created.', $t_args));
     }
     else {
       $logger->notice('@type: updated %label.', $context);
-      drupal_set_message($this->t('@type %label has been updated.', $t_args));
+      $this->messenger()->addStatus($this->t('@type %label has been updated.', $t_args));
     }
 
     $form_state->setRedirectUrl($this->entity->toUrl('canonical'));
diff --git a/core/modules/media/src/MediaTypeForm.php b/core/modules/media/src/MediaTypeForm.php
index 0ba5ee51591f..49944800efe9 100644
--- a/core/modules/media/src/MediaTypeForm.php
+++ b/core/modules/media/src/MediaTypeForm.php
@@ -369,10 +369,10 @@ public function save(array $form, FormStateInterface $form_state) {
 
     $t_args = ['%name' => $media_type->label()];
     if ($status === SAVED_UPDATED) {
-      drupal_set_message($this->t('The media type %name has been updated.', $t_args));
+      $this->messenger()->addStatus($this->t('The media type %name has been updated.', $t_args));
     }
     elseif ($status === SAVED_NEW) {
-      drupal_set_message($this->t('The media type %name has been added.', $t_args));
+      $this->messenger()->addStatus($this->t('The media type %name has been added.', $t_args));
       $this->logger('media')->notice('Added media type %name.', $t_args);
     }
 
diff --git a/core/modules/menu_link_content/src/Form/MenuLinkContentForm.php b/core/modules/menu_link_content/src/Form/MenuLinkContentForm.php
index 7175c1bb25cd..60e086b13329 100644
--- a/core/modules/menu_link_content/src/Form/MenuLinkContentForm.php
+++ b/core/modules/menu_link_content/src/Form/MenuLinkContentForm.php
@@ -130,14 +130,14 @@ public function save(array $form, FormStateInterface $form_state) {
     $saved = $menu_link->save();
 
     if ($saved) {
-      drupal_set_message($this->t('The menu link has been saved.'));
+      $this->messenger()->addStatus($this->t('The menu link has been saved.'));
       $form_state->setRedirect(
         'entity.menu_link_content.canonical',
         ['menu_link_content' => $menu_link->id()]
       );
     }
     else {
-      drupal_set_message($this->t('There was an error saving the menu link.'), 'error');
+      $this->messenger()->addError($this->t('There was an error saving the menu link.'));
       $form_state->setRebuild();
     }
   }
diff --git a/core/modules/menu_ui/src/Form/MenuLinkEditForm.php b/core/modules/menu_ui/src/Form/MenuLinkEditForm.php
index 6cb50da1c484..1afafd64449b 100644
--- a/core/modules/menu_ui/src/Form/MenuLinkEditForm.php
+++ b/core/modules/menu_ui/src/Form/MenuLinkEditForm.php
@@ -91,7 +91,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) {
   public function submitForm(array &$form, FormStateInterface $form_state) {
     $link = $form['#plugin_form']->submitConfigurationForm($form, $form_state);
 
-    drupal_set_message($this->t('The menu link has been saved.'));
+    $this->messenger()->addStatus($this->t('The menu link has been saved.'));
     $form_state->setRedirect(
       'entity.menu.edit_form',
       ['menu' => $link->getMenuName()]
diff --git a/core/modules/menu_ui/src/Form/MenuLinkResetForm.php b/core/modules/menu_ui/src/Form/MenuLinkResetForm.php
index de9dccb9ed99..ae307bcd72b9 100644
--- a/core/modules/menu_ui/src/Form/MenuLinkResetForm.php
+++ b/core/modules/menu_ui/src/Form/MenuLinkResetForm.php
@@ -102,7 +102,7 @@ public function buildForm(array $form, FormStateInterface $form_state, MenuLinkI
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
     $this->link = $this->menuLinkManager->resetLink($this->link->getPluginId());
-    drupal_set_message($this->t('The menu link was reset to its default settings.'));
+    $this->messenger()->addStatus($this->t('The menu link was reset to its default settings.'));
     $form_state->setRedirectUrl($this->getCancelUrl());
   }
 
diff --git a/core/modules/menu_ui/src/MenuForm.php b/core/modules/menu_ui/src/MenuForm.php
index aec2c49eb0ae..9291fda0bf16 100644
--- a/core/modules/menu_ui/src/MenuForm.php
+++ b/core/modules/menu_ui/src/MenuForm.php
@@ -166,11 +166,11 @@ public function save(array $form, FormStateInterface $form_state) {
     $status = $menu->save();
     $edit_link = $this->entity->link($this->t('Edit'));
     if ($status == SAVED_UPDATED) {
-      drupal_set_message($this->t('Menu %label has been updated.', ['%label' => $menu->label()]));
+      $this->messenger()->addStatus($this->t('Menu %label has been updated.', ['%label' => $menu->label()]));
       $this->logger('menu')->notice('Menu %label has been updated.', ['%label' => $menu->label(), 'link' => $edit_link]);
     }
     else {
-      drupal_set_message($this->t('Menu %label has been added.', ['%label' => $menu->label()]));
+      $this->messenger()->addStatus($this->t('Menu %label has been added.', ['%label' => $menu->label()]));
       $this->logger('menu')->notice('Menu %label has been added.', ['%label' => $menu->label(), 'link' => $edit_link]);
     }
 
diff --git a/core/modules/migrate_drupal_ui/migrate_drupal_ui.install b/core/modules/migrate_drupal_ui/migrate_drupal_ui.install
index c6925b9b8df5..5962ee1f8786 100644
--- a/core/modules/migrate_drupal_ui/migrate_drupal_ui.install
+++ b/core/modules/migrate_drupal_ui/migrate_drupal_ui.install
@@ -12,5 +12,5 @@
  */
 function migrate_drupal_ui_install() {
   $url = Url::fromRoute('migrate_drupal_ui.upgrade')->toString();
-  drupal_set_message(t('The Migrate Drupal UI module has been enabled. Proceed to the <a href=":url">upgrade form</a>.', [':url' => $url]));
+  \Drupal::messenger()->addStatus(t('The Migrate Drupal UI module has been enabled. Proceed to the <a href=":url">upgrade form</a>.', [':url' => $url]));
 }
diff --git a/core/modules/migrate_drupal_ui/src/Batch/MigrateUpgradeImportBatch.php b/core/modules/migrate_drupal_ui/src/Batch/MigrateUpgradeImportBatch.php
index 7145b8d24930..a00f1582bb7e 100644
--- a/core/modules/migrate_drupal_ui/src/Batch/MigrateUpgradeImportBatch.php
+++ b/core/modules/migrate_drupal_ui/src/Batch/MigrateUpgradeImportBatch.php
@@ -257,24 +257,24 @@ public static function finished($success, $results, $operations, $elapsed) {
 
     // If we had any successes log that for the user.
     if ($successes > 0) {
-      drupal_set_message(\Drupal::translation()
+      \Drupal::messenger()->addStatus(\Drupal::translation()
         ->formatPlural($successes, 'Completed 1 upgrade task successfully', 'Completed @count upgrade tasks successfully'));
     }
     // If we had failures, log them and show the migration failed.
     if ($failures > 0) {
-      drupal_set_message(\Drupal::translation()
+      \Drupal::messenger()->addStatus(\Drupal::translation()
         ->formatPlural($failures, '1 upgrade failed', '@count upgrades failed'));
-      drupal_set_message(t('Upgrade process not completed'), 'error');
+      \Drupal::messenger()->addError(t('Upgrade process not completed'));
     }
     else {
       // Everything went off without a hitch. We may not have had successes
       // but we didn't have failures so this is fine.
-      drupal_set_message(t('Congratulations, you upgraded Drupal!'));
+      \Drupal::messenger()->addStatus(t('Congratulations, you upgraded Drupal!'));
     }
 
     if (\Drupal::moduleHandler()->moduleExists('dblog')) {
       $url = Url::fromRoute('migrate_drupal_ui.log');
-      drupal_set_message(Link::fromTextAndUrl(new TranslatableMarkup('Review the detailed upgrade log'), $url), $failures ? 'error' : 'status');
+      \Drupal::messenger()->addMessage(Link::fromTextAndUrl(new TranslatableMarkup('Review the detailed upgrade log'), $url), $failures ? 'error' : 'status');
     }
   }
 
diff --git a/core/modules/node/node.admin.inc b/core/modules/node/node.admin.inc
index b96ee5aff620..fe48692a8473 100644
--- a/core/modules/node/node.admin.inc
+++ b/core/modules/node/node.admin.inc
@@ -60,7 +60,7 @@ function node_mass_update(array $nodes, array $updates, $langcode = NULL, $load
       }
       _node_mass_update_helper($node, $updates, $langcode);
     }
-    drupal_set_message(t('The update has been performed.'));
+    \Drupal::messenger()->addStatus(t('The update has been performed.'));
   }
 }
 
@@ -164,16 +164,16 @@ function _node_mass_update_batch_process(array $nodes, array $updates, $langcode
  */
 function _node_mass_update_batch_finished($success, $results, $operations) {
   if ($success) {
-    drupal_set_message(t('The update has been performed.'));
+    \Drupal::messenger()->addStatus(t('The update has been performed.'));
   }
   else {
-    drupal_set_message(t('An error occurred and processing did not complete.'), 'error');
+    \Drupal::messenger()->addError(t('An error occurred and processing did not complete.'));
     $message = \Drupal::translation()->formatPlural(count($results), '1 item successfully processed:', '@count items successfully processed:');
     $item_list = [
       '#theme' => 'item_list',
       '#items' => $results,
     ];
     $message .= \Drupal::service('renderer')->render($item_list);
-    drupal_set_message($message);
+    \Drupal::messenger()->addStatus($message);
   }
 }
diff --git a/core/modules/node/node.module b/core/modules/node/node.module
index 208deb5786ca..9930fa89aa28 100644
--- a/core/modules/node/node.module
+++ b/core/modules/node/node.module
@@ -104,7 +104,7 @@ function node_help($route_name, RouteMatchInterface $route_match) {
     else {
       $message = t('The content access permissions need to be rebuilt. <a href=":node_access_rebuild">Rebuild permissions</a>.', [':node_access_rebuild' => \Drupal::url('node.configure_rebuild_confirm')]);
     }
-    drupal_set_message($message, 'error');
+    \Drupal::messenger()->addError($message);
   }
 
   switch ($route_name) {
@@ -1221,7 +1221,7 @@ function node_access_rebuild($batch_mode = FALSE) {
   }
 
   if (!isset($batch)) {
-    drupal_set_message(t('Content permissions have been rebuilt.'));
+    \Drupal::messenger()->addStatus(t('Content permissions have been rebuilt.'));
     node_access_needs_rebuild(FALSE);
   }
 }
@@ -1294,11 +1294,11 @@ function _node_access_rebuild_batch_operation(&$context) {
  */
 function _node_access_rebuild_batch_finished($success, $results, $operations) {
   if ($success) {
-    drupal_set_message(t('The content access permissions have been rebuilt.'));
+    \Drupal::messenger()->addStatus(t('The content access permissions have been rebuilt.'));
     node_access_needs_rebuild(FALSE);
   }
   else {
-    drupal_set_message(t('The content access permissions have not been properly rebuilt.'), 'error');
+    \Drupal::messenger()->addError(t('The content access permissions have not been properly rebuilt.'));
   }
 }
 
diff --git a/core/modules/node/src/Entity/NodeType.php b/core/modules/node/src/Entity/NodeType.php
index 6daa45dad9b5..56efb8608dd1 100644
--- a/core/modules/node/src/Entity/NodeType.php
+++ b/core/modules/node/src/Entity/NodeType.php
@@ -186,7 +186,7 @@ public function postSave(EntityStorageInterface $storage, $update = TRUE) {
     if ($update && $this->getOriginalId() != $this->id()) {
       $update_count = node_type_update_nodes($this->getOriginalId(), $this->id());
       if ($update_count) {
-        drupal_set_message(\Drupal::translation()->formatPlural($update_count,
+        \Drupal::messenger()->addStatus(\Drupal::translation()->formatPlural($update_count,
           'Changed the content type of 1 post from %old-type to %type.',
           'Changed the content type of @count posts from %old-type to %type.',
           [
diff --git a/core/modules/node/src/Form/NodeRevisionDeleteForm.php b/core/modules/node/src/Form/NodeRevisionDeleteForm.php
index 47e77990ccab..d2145a55fb34 100644
--- a/core/modules/node/src/Form/NodeRevisionDeleteForm.php
+++ b/core/modules/node/src/Form/NodeRevisionDeleteForm.php
@@ -118,7 +118,12 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
 
     $this->logger('content')->notice('@type: deleted %title revision %revision.', ['@type' => $this->revision->bundle(), '%title' => $this->revision->label(), '%revision' => $this->revision->getRevisionId()]);
     $node_type = $this->nodeTypeStorage->load($this->revision->bundle())->label();
-    drupal_set_message(t('Revision from %revision-date of @type %title has been deleted.', ['%revision-date' => format_date($this->revision->getRevisionCreationTime()), '@type' => $node_type, '%title' => $this->revision->label()]));
+    $this->messenger()
+      ->addStatus($this->t('Revision from %revision-date of @type %title has been deleted.', [
+        '%revision-date' => format_date($this->revision->getRevisionCreationTime()),
+        '@type' => $node_type,
+        '%title' => $this->revision->label(),
+      ]));
     $form_state->setRedirect(
       'entity.node.canonical',
       ['node' => $this->revision->id()]
diff --git a/core/modules/node/src/Form/NodeRevisionRevertForm.php b/core/modules/node/src/Form/NodeRevisionRevertForm.php
index 246654bcf78a..cbd7e868ff02 100644
--- a/core/modules/node/src/Form/NodeRevisionRevertForm.php
+++ b/core/modules/node/src/Form/NodeRevisionRevertForm.php
@@ -134,7 +134,12 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     $this->revision->save();
 
     $this->logger('content')->notice('@type: reverted %title revision %revision.', ['@type' => $this->revision->bundle(), '%title' => $this->revision->label(), '%revision' => $this->revision->getRevisionId()]);
-    drupal_set_message(t('@type %title has been reverted to the revision from %revision-date.', ['@type' => node_get_type_label($this->revision), '%title' => $this->revision->label(), '%revision-date' => $this->dateFormatter->format($original_revision_timestamp)]));
+    $this->messenger()
+      ->addStatus($this->t('@type %title has been reverted to the revision from %revision-date.', [
+        '@type' => node_get_type_label($this->revision),
+        '%title' => $this->revision->label(),
+        '%revision-date' => $this->dateFormatter->format($original_revision_timestamp),
+      ]));
     $form_state->setRedirect(
       'entity.node.version_history',
       ['node' => $this->revision->id()]
diff --git a/core/modules/node/src/NodeForm.php b/core/modules/node/src/NodeForm.php
index 0ad34ad24200..f7756349227a 100644
--- a/core/modules/node/src/NodeForm.php
+++ b/core/modules/node/src/NodeForm.php
@@ -285,11 +285,11 @@ public function save(array $form, FormStateInterface $form_state) {
 
     if ($insert) {
       $this->logger('content')->notice('@type: added %title.', $context);
-      drupal_set_message(t('@type %title has been created.', $t_args));
+      $this->messenger()->addStatus($this->t('@type %title has been created.', $t_args));
     }
     else {
       $this->logger('content')->notice('@type: updated %title.', $context);
-      drupal_set_message(t('@type %title has been updated.', $t_args));
+      $this->messenger()->addStatus($this->t('@type %title has been updated.', $t_args));
     }
 
     if ($node->id()) {
@@ -312,7 +312,7 @@ public function save(array $form, FormStateInterface $form_state) {
     else {
       // In the unlikely case something went wrong on save, the node will be
       // rebuilt and node form redisplayed the same way as in preview.
-      drupal_set_message(t('The post could not be saved.'), 'error');
+      $this->messenger()->addError($this->t('The post could not be saved.'));
       $form_state->setRebuild();
     }
   }
diff --git a/core/modules/node/src/NodeTypeForm.php b/core/modules/node/src/NodeTypeForm.php
index 9eec40c70087..148c1ff6839a 100644
--- a/core/modules/node/src/NodeTypeForm.php
+++ b/core/modules/node/src/NodeTypeForm.php
@@ -225,11 +225,11 @@ public function save(array $form, FormStateInterface $form_state) {
     $t_args = ['%name' => $type->label()];
 
     if ($status == SAVED_UPDATED) {
-      drupal_set_message(t('The content type %name has been updated.', $t_args));
+      $this->messenger()->addStatus($this->t('The content type %name has been updated.', $t_args));
     }
     elseif ($status == SAVED_NEW) {
       node_add_body_field($type);
-      drupal_set_message(t('The content type %name has been added.', $t_args));
+      $this->messenger()->addStatus($this->t('The content type %name has been added.', $t_args));
       $context = array_merge($t_args, ['link' => $type->link($this->t('View'), 'collection')]);
       $this->logger('node')->notice('Added content type %name.', $context);
     }
diff --git a/core/modules/node/src/Plugin/Search/NodeSearch.php b/core/modules/node/src/Plugin/Search/NodeSearch.php
index c200f34b6107..52c121e69d67 100644
--- a/core/modules/node/src/Plugin/Search/NodeSearch.php
+++ b/core/modules/node/src/Plugin/Search/NodeSearch.php
@@ -13,6 +13,7 @@
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\Core\Language\LanguageInterface;
 use Drupal\Core\Language\LanguageManagerInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Core\Session\AccountInterface;
 use Drupal\Core\Access\AccessibleInterface;
 use Drupal\Core\Database\Query\Condition;
@@ -114,6 +115,13 @@ class NodeSearch extends ConfigurableSearchPluginBase implements AccessibleInter
    */
   const ADVANCED_FORM = 'advanced-form';
 
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
   /**
    * {@inheritdoc}
    */
@@ -128,6 +136,7 @@ public static function create(ContainerInterface $container, array $configuratio
       $container->get('config.factory')->get('search.settings'),
       $container->get('language_manager'),
       $container->get('renderer'),
+      $container->get('messenger'),
       $container->get('current_user')
     );
   }
@@ -153,16 +162,19 @@ public static function create(ContainerInterface $container, array $configuratio
    *   The language manager.
    * @param \Drupal\Core\Render\RendererInterface $renderer
    *   The renderer.
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   The messenger.
    * @param \Drupal\Core\Session\AccountInterface $account
    *   The $account object to use for checking for access to advanced search.
    */
-  public function __construct(array $configuration, $plugin_id, $plugin_definition, Connection $database, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, Config $search_settings, LanguageManagerInterface $language_manager, RendererInterface $renderer, AccountInterface $account = NULL) {
+  public function __construct(array $configuration, $plugin_id, $plugin_definition, Connection $database, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, Config $search_settings, LanguageManagerInterface $language_manager, RendererInterface $renderer, MessengerInterface $messenger, AccountInterface $account = NULL) {
     $this->database = $database;
     $this->entityManager = $entity_manager;
     $this->moduleHandler = $module_handler;
     $this->searchSettings = $search_settings;
     $this->languageManager = $language_manager;
     $this->renderer = $renderer;
+    $this->messenger = $messenger;
     $this->account = $account;
     parent::__construct($configuration, $plugin_id, $plugin_definition);
 
@@ -289,15 +301,15 @@ protected function findResults() {
     $status = $query->getStatus();
 
     if ($status & SearchQuery::EXPRESSIONS_IGNORED) {
-      drupal_set_message($this->t('Your search used too many AND/OR expressions. Only the first @count terms were included in this search.', ['@count' => $this->searchSettings->get('and_or_limit')]), 'warning');
+      $this->messenger->addWarning($this->t('Your search used too many AND/OR expressions. Only the first @count terms were included in this search.', ['@count' => $this->searchSettings->get('and_or_limit')]));
     }
 
     if ($status & SearchQuery::LOWER_CASE_OR) {
-      drupal_set_message($this->t('Search for either of the two terms with uppercase <strong>OR</strong>. For example, <strong>cats OR dogs</strong>.'), 'warning');
+      $this->messenger->addWarning($this->t('Search for either of the two terms with uppercase <strong>OR</strong>. For example, <strong>cats OR dogs</strong>.'));
     }
 
     if ($status & SearchQuery::NO_POSITIVE_KEYWORDS) {
-      drupal_set_message($this->formatPlural($this->searchSettings->get('index.minimum_word_size'), 'You must include at least one keyword to match in the content, and punctuation is ignored.', 'You must include at least one keyword to match in the content. Keywords must be at least @count characters, and punctuation is ignored.'), 'warning');
+      $this->messenger->addWarning($this->formatPlural($this->searchSettings->get('index.minimum_word_size'), 'You must include at least one keyword to match in the content, and punctuation is ignored.', 'You must include at least one keyword to match in the content. Keywords must be at least @count characters, and punctuation is ignored.'));
     }
 
     return $find;
diff --git a/core/modules/node/tests/modules/node_test/node_test.module b/core/modules/node/tests/modules/node_test/node_test.module
index a2f06decced2..56aef63c618e 100644
--- a/core/modules/node/tests/modules/node_test/node_test.module
+++ b/core/modules/node/tests/modules/node_test/node_test.module
@@ -182,10 +182,10 @@ function node_test_node_insert(NodeInterface $node) {
  */
 function node_test_form_alter(&$form, FormStateInterface $form_state, $form_id) {
   if (!$form_state->get('node_test_form_alter')) {
-    drupal_set_message('Storage is not set');
+    \Drupal::messenger()->addStatus('Storage is not set');
     $form_state->set('node_test_form_alter', TRUE);
   }
   else {
-    drupal_set_message('Storage is set');
+    \Drupal::messenger()->addStatus('Storage is set');
   }
 }
diff --git a/core/modules/node/tests/src/Unit/Plugin/views/field/NodeBulkFormTest.php b/core/modules/node/tests/src/Unit/Plugin/views/field/NodeBulkFormTest.php
index eb92f8cb0a95..5599f4a13b29 100644
--- a/core/modules/node/tests/src/Unit/Plugin/views/field/NodeBulkFormTest.php
+++ b/core/modules/node/tests/src/Unit/Plugin/views/field/NodeBulkFormTest.php
@@ -54,6 +54,8 @@ public function testConstructor() {
 
     $language_manager = $this->getMock('Drupal\Core\Language\LanguageManagerInterface');
 
+    $messenger = $this->getMock('Drupal\Core\Messenger\MessengerInterface');
+
     $views_data = $this->getMockBuilder('Drupal\views\ViewsData')
       ->disableOriginalConstructor()
       ->getMock();
@@ -84,7 +86,7 @@ public function testConstructor() {
     $definition['title'] = '';
     $options = [];
 
-    $node_bulk_form = new NodeBulkForm([], 'node_bulk_form', $definition, $entity_manager, $language_manager);
+    $node_bulk_form = new NodeBulkForm([], 'node_bulk_form', $definition, $entity_manager, $language_manager, $messenger);
     $node_bulk_form->init($executable, $display, $options);
 
     $this->assertAttributeEquals(array_slice($actions, 0, -1, TRUE), 'actions', $node_bulk_form);
diff --git a/core/modules/path/src/Form/PathFormBase.php b/core/modules/path/src/Form/PathFormBase.php
index 5a54c08b482d..2aa785cd7383 100644
--- a/core/modules/path/src/Form/PathFormBase.php
+++ b/core/modules/path/src/Form/PathFormBase.php
@@ -212,7 +212,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
 
     $this->aliasStorage->save($source, $alias, $langcode, $pid);
 
-    drupal_set_message($this->t('The alias has been saved.'));
+    $this->messenger()->addStatus($this->t('The alias has been saved.'));
     $form_state->setRedirect('path.admin_overview');
   }
 
diff --git a/core/modules/responsive_image/src/ResponsiveImageStyleForm.php b/core/modules/responsive_image/src/ResponsiveImageStyleForm.php
index 424047390053..3a709519d09e 100644
--- a/core/modules/responsive_image/src/ResponsiveImageStyleForm.php
+++ b/core/modules/responsive_image/src/ResponsiveImageStyleForm.php
@@ -276,7 +276,7 @@ public function save(array $form, FormStateInterface $form_state) {
     $responsive_image_style->save();
 
     $this->logger('responsive_image')->notice('Responsive image style @label saved.', ['@label' => $responsive_image_style->label()]);
-    drupal_set_message($this->t('Responsive image style %label saved.', ['%label' => $responsive_image_style->label()]));
+    $this->messenger()->addStatus($this->t('Responsive image style %label saved.', ['%label' => $responsive_image_style->label()]));
 
     // Redirect to edit form after creating a new responsive image style or
     // after selecting another breakpoint group.
diff --git a/core/modules/search/src/Controller/SearchController.php b/core/modules/search/src/Controller/SearchController.php
index e0b6466aa199..f6449dfc25e3 100644
--- a/core/modules/search/src/Controller/SearchController.php
+++ b/core/modules/search/src/Controller/SearchController.php
@@ -104,7 +104,7 @@ public function view(Request $request, SearchPageInterface $entity) {
       else {
         // The search not being executable means that no keywords or other
         // conditions were entered.
-        drupal_set_message($this->t('Please enter some keywords.'), 'error');
+        $this->messenger()->addError($this->t('Please enter some keywords.'));
       }
     }
 
@@ -206,10 +206,10 @@ public function performOperation(SearchPageInterface $search_page, $op) {
     $search_page->$op()->save();
 
     if ($op == 'enable') {
-      drupal_set_message($this->t('The %label search page has been enabled.', ['%label' => $search_page->label()]));
+      $this->messenger()->addStatus($this->t('The %label search page has been enabled.', ['%label' => $search_page->label()]));
     }
     elseif ($op == 'disable') {
-      drupal_set_message($this->t('The %label search page has been disabled.', ['%label' => $search_page->label()]));
+      $this->messenger()->addStatus($this->t('The %label search page has been disabled.', ['%label' => $search_page->label()]));
     }
 
     $url = $search_page->urlInfo('collection');
@@ -229,7 +229,7 @@ public function setAsDefault(SearchPageInterface $search_page) {
     // Set the default page to this search page.
     $this->searchPageRepository->setDefaultSearchPage($search_page);
 
-    drupal_set_message($this->t('The default search page is now %label. Be sure to check the ordering of your search pages.', ['%label' => $search_page->label()]));
+    $this->messenger()->addStatus($this->t('The default search page is now %label. Be sure to check the ordering of your search pages.', ['%label' => $search_page->label()]));
     return $this->redirect('entity.search_page.collection');
   }
 
diff --git a/core/modules/search/src/Form/ReindexConfirm.php b/core/modules/search/src/Form/ReindexConfirm.php
index 2a30cb5b7bae..a9a2cd050dc6 100644
--- a/core/modules/search/src/Form/ReindexConfirm.php
+++ b/core/modules/search/src/Form/ReindexConfirm.php
@@ -65,7 +65,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       foreach ($search_page_repository->getIndexableSearchPages() as $entity) {
         $entity->getPlugin()->markForReindex();
       }
-      drupal_set_message($this->t('All search indexes will be rebuilt.'));
+      $this->messenger()->addStatus($this->t('All search indexes will be rebuilt.'));
       $form_state->setRedirectUrl($this->getCancelUrl());
     }
   }
diff --git a/core/modules/search/src/Form/SearchPageAddForm.php b/core/modules/search/src/Form/SearchPageAddForm.php
index 6f5c142d6e41..492d6c0af734 100644
--- a/core/modules/search/src/Form/SearchPageAddForm.php
+++ b/core/modules/search/src/Form/SearchPageAddForm.php
@@ -41,7 +41,7 @@ public function save(array $form, FormStateInterface $form_state) {
 
     parent::save($form, $form_state);
 
-    drupal_set_message($this->t('The %label search page has been added.', ['%label' => $this->entity->label()]));
+    $this->messenger()->addStatus($this->t('The %label search page has been added.', ['%label' => $this->entity->label()]));
   }
 
 }
diff --git a/core/modules/search/src/Form/SearchPageEditForm.php b/core/modules/search/src/Form/SearchPageEditForm.php
index afbcfbc360ee..28fda7f958ab 100644
--- a/core/modules/search/src/Form/SearchPageEditForm.php
+++ b/core/modules/search/src/Form/SearchPageEditForm.php
@@ -26,7 +26,7 @@ protected function actions(array $form, FormStateInterface $form_state) {
   public function save(array $form, FormStateInterface $form_state) {
     parent::save($form, $form_state);
 
-    drupal_set_message($this->t('The %label search page has been updated.', ['%label' => $this->entity->label()]));
+    $this->messenger()->addStatus($this->t('The %label search page has been updated.', ['%label' => $this->entity->label()]));
   }
 
 }
diff --git a/core/modules/search/src/SearchPageListBuilder.php b/core/modules/search/src/SearchPageListBuilder.php
index 9a8f6deb302e..9442b6961394 100644
--- a/core/modules/search/src/SearchPageListBuilder.php
+++ b/core/modules/search/src/SearchPageListBuilder.php
@@ -10,6 +10,7 @@
 use Drupal\Core\Form\ConfigFormBaseTrait;
 use Drupal\Core\Form\FormInterface;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Core\Url;
 use Symfony\Component\DependencyInjection\ContainerInterface;
 
@@ -42,6 +43,13 @@ class SearchPageListBuilder extends DraggableListBuilder implements FormInterfac
    */
   protected $searchManager;
 
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
   /**
    * Constructs a new SearchPageListBuilder object.
    *
@@ -53,11 +61,14 @@ class SearchPageListBuilder extends DraggableListBuilder implements FormInterfac
    *   The search plugin manager.
    * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
    *   The factory for configuration objects.
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   The messenger.
    */
-  public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, SearchPluginManager $search_manager, ConfigFactoryInterface $config_factory) {
+  public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, SearchPluginManager $search_manager, ConfigFactoryInterface $config_factory, MessengerInterface $messenger) {
     parent::__construct($entity_type, $storage);
     $this->configFactory = $config_factory;
     $this->searchManager = $search_manager;
+    $this->messenger = $messenger;
   }
 
   /**
@@ -68,7 +79,8 @@ public static function createInstance(ContainerInterface $container, EntityTypeI
       $entity_type,
       $container->get('entity.manager')->getStorage($entity_type->id()),
       $container->get('plugin.manager.search'),
-      $container->get('config.factory')
+      $container->get('config.factory'),
+      $container->get('messenger')
     );
   }
 
@@ -333,7 +345,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $search_settings->set('index.overlap_cjk', $form_state->getValue('overlap_cjk'));
       // Specifically mark items in the default index for reindexing, since
       // these settings are used in the search_index() function.
-      drupal_set_message($this->t('The default search index will be rebuilt.'));
+      $this->messenger->addStatus($this->t('The default search index will be rebuilt.'));
       search_mark_for_reindex();
     }
 
@@ -342,7 +354,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       ->set('logging', $form_state->getValue('logging'))
       ->save();
 
-    drupal_set_message($this->t('The configuration options have been saved.'));
+    $this->messenger->addStatus($this->t('The configuration options have been saved.'));
   }
 
   /**
diff --git a/core/modules/search/tests/modules/search_embedded_form/src/Form/SearchEmbeddedForm.php b/core/modules/search/tests/modules/search_embedded_form/src/Form/SearchEmbeddedForm.php
index b1e26ca53ffb..5f13ee93940c 100644
--- a/core/modules/search/tests/modules/search_embedded_form/src/Form/SearchEmbeddedForm.php
+++ b/core/modules/search/tests/modules/search_embedded_form/src/Form/SearchEmbeddedForm.php
@@ -50,7 +50,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     $state = \Drupal::state();
     $submit_count = (int) $state->get('search_embedded_form.submit_count');
     $state->set('search_embedded_form.submit_count', $submit_count + 1);
-    drupal_set_message($this->t('Test form was submitted'));
+    $this->messenger()->addStatus($this->t('Test form was submitted'));
   }
 
 }
diff --git a/core/modules/search/tests/modules/search_langcode_test/search_langcode_test.module b/core/modules/search/tests/modules/search_langcode_test/search_langcode_test.module
index c7d96245df12..38330602a5a6 100644
--- a/core/modules/search/tests/modules/search_langcode_test/search_langcode_test.module
+++ b/core/modules/search/tests/modules/search_langcode_test/search_langcode_test.module
@@ -19,13 +19,13 @@ function search_langcode_test_search_preprocess($text, $langcode = NULL) {
     // Prints the langcode for testPreprocessLangcode() and adds some
     // extra text.
     else {
-      drupal_set_message('Langcode Preprocess Test: ' . $langcode);
+      \Drupal::messenger()->addStatus('Langcode Preprocess Test: ' . $langcode);
       $text .= 'Additional text';
     }
   }
   // Prints the langcode for testPreprocessLangcode().
   elseif (isset($langcode)) {
-    drupal_set_message('Langcode Preprocess Test: ' . $langcode);
+    \Drupal::messenger()->addStatus('Langcode Preprocess Test: ' . $langcode);
 
     // Preprocessing for the excerpt test.
     if ($langcode == 'ex') {
diff --git a/core/modules/shortcut/src/Controller/ShortcutController.php b/core/modules/shortcut/src/Controller/ShortcutController.php
index 4f33b0b55573..dbb24e582e92 100644
--- a/core/modules/shortcut/src/Controller/ShortcutController.php
+++ b/core/modules/shortcut/src/Controller/ShortcutController.php
@@ -40,10 +40,10 @@ public function deleteShortcutLinkInline(ShortcutInterface $shortcut) {
 
     try {
       $shortcut->delete();
-      drupal_set_message($this->t('The shortcut %title has been deleted.', ['%title' => $label]));
+      $this->messenger()->addStatus($this->t('The shortcut %title has been deleted.', ['%title' => $label]));
     }
     catch (\Exception $e) {
-      drupal_set_message($this->t('Unable to delete the shortcut for %title.', ['%title' => $label]), 'error');
+      $this->messenger()->addStatus($this->t('Unable to delete the shortcut for %title.', ['%title' => $label]), 'error');
     }
 
     return $this->redirect('<front>');
diff --git a/core/modules/shortcut/src/Controller/ShortcutSetController.php b/core/modules/shortcut/src/Controller/ShortcutSetController.php
index 58a68d70e0d4..541d43796cf3 100644
--- a/core/modules/shortcut/src/Controller/ShortcutSetController.php
+++ b/core/modules/shortcut/src/Controller/ShortcutSetController.php
@@ -65,10 +65,10 @@ public function addShortcutLinkInline(ShortcutSetInterface $shortcut_set, Reques
 
       try {
         $shortcut->save();
-        drupal_set_message($this->t('Added a shortcut for %title.', ['%title' => $shortcut->label()]));
+        $this->messenger()->addStatus($this->t('Added a shortcut for %title.', ['%title' => $shortcut->label()]));
       }
       catch (\Exception $e) {
-        drupal_set_message($this->t('Unable to add a shortcut for %title.', ['%title' => $shortcut->label()]), 'error');
+        $this->messenger()->addError($this->t('Unable to add a shortcut for %title.', ['%title' => $shortcut->label()]));
       }
 
       return $this->redirect('<front>');
diff --git a/core/modules/shortcut/src/Form/SetCustomize.php b/core/modules/shortcut/src/Form/SetCustomize.php
index 20094aa2c304..027f023617b7 100644
--- a/core/modules/shortcut/src/Form/SetCustomize.php
+++ b/core/modules/shortcut/src/Form/SetCustomize.php
@@ -106,7 +106,7 @@ public function save(array $form, FormStateInterface $form_state) {
       $shortcut->setWeight($weight);
       $shortcut->save();
     }
-    drupal_set_message(t('The shortcut set has been updated.'));
+    $this->messenger()->addStatus($this->t('The shortcut set has been updated.'));
   }
 
 }
diff --git a/core/modules/shortcut/src/Form/SwitchShortcutSet.php b/core/modules/shortcut/src/Form/SwitchShortcutSet.php
index 726af172cde2..a71aba28e084 100644
--- a/core/modules/shortcut/src/Form/SwitchShortcutSet.php
+++ b/core/modules/shortcut/src/Form/SwitchShortcutSet.php
@@ -188,10 +188,10 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       if ($account_is_user) {
         // Only administrators can create new shortcut sets, so we know they have
         // access to switch back.
-        drupal_set_message($this->t('You are now using the new %set_name shortcut set. You can edit it from this page or <a href=":switch-url">switch back to a different one.</a>', $replacements));
+        $this->messenger()->addStatus($this->t('You are now using the new %set_name shortcut set. You can edit it from this page or <a href=":switch-url">switch back to a different one.</a>', $replacements));
       }
       else {
-        drupal_set_message($this->t('%user is now using a new shortcut set called %set_name. You can edit it from this page.', $replacements));
+        $this->messenger()->addStatus($this->t('%user is now using a new shortcut set called %set_name. You can edit it from this page.', $replacements));
       }
       $form_state->setRedirect(
         'entity.shortcut_set.customize_form',
@@ -206,7 +206,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
         '%user' => $this->user->getDisplayName(),
         '%set_name' => $set->label(),
       ];
-      drupal_set_message($account_is_user ? $this->t('You are now using the %set_name shortcut set.', $replacements) : $this->t('%user is now using the %set_name shortcut set.', $replacements));
+      $this->messenger()->addStatus($account_is_user ? $this->t('You are now using the %set_name shortcut set.', $replacements) : $this->t('%user is now using the %set_name shortcut set.', $replacements));
     }
 
     // Assign the shortcut set to the provided user account.
diff --git a/core/modules/shortcut/src/ShortcutForm.php b/core/modules/shortcut/src/ShortcutForm.php
index fa62cdb685f9..26a52629b2f7 100644
--- a/core/modules/shortcut/src/ShortcutForm.php
+++ b/core/modules/shortcut/src/ShortcutForm.php
@@ -42,7 +42,7 @@ public function save(array $form, FormStateInterface $form_state) {
     else {
       $message = $this->t('Added a shortcut for %title.', ['%title' => $view_link]);
     }
-    drupal_set_message($message);
+    $this->messenger()->addStatus($message);
 
     $form_state->setRedirect(
       'entity.shortcut_set.customize_form',
diff --git a/core/modules/shortcut/src/ShortcutSetForm.php b/core/modules/shortcut/src/ShortcutSetForm.php
index 3c8f4a798a69..2a27cb702999 100644
--- a/core/modules/shortcut/src/ShortcutSetForm.php
+++ b/core/modules/shortcut/src/ShortcutSetForm.php
@@ -53,10 +53,10 @@ public function save(array $form, FormStateInterface $form_state) {
     $entity->save();
 
     if ($is_new) {
-      drupal_set_message(t('The %set_name shortcut set has been created. You can edit it from this page.', ['%set_name' => $entity->label()]));
+      $this->messenger()->addStatus($this->t('The %set_name shortcut set has been created. You can edit it from this page.', ['%set_name' => $entity->label()]));
     }
     else {
-      drupal_set_message(t('Updated set name to %set-name.', ['%set-name' => $entity->label()]));
+      $this->messenger()->addStatus($this->t('Updated set name to %set-name.', ['%set-name' => $entity->label()]));
     }
     $form_state->setRedirectUrl($this->entity->urlInfo('customize-form'));
   }
diff --git a/core/modules/simpletest/simpletest.module b/core/modules/simpletest/simpletest.module
index dd05ddc1ca71..4ace6e45948e 100644
--- a/core/modules/simpletest/simpletest.module
+++ b/core/modules/simpletest/simpletest.module
@@ -475,7 +475,7 @@ function _simpletest_batch_operation($test_list_init, $test_id, &$context) {
  */
 function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
   if ($success) {
-    drupal_set_message(t('The test run finished in @elapsed.', ['@elapsed' => $elapsed]));
+    \Drupal::messenger()->addStatus(t('The test run finished in @elapsed.', ['@elapsed' => $elapsed]));
   }
   else {
     // Use the test_id passed as a parameter to _simpletest_batch_operation().
@@ -487,8 +487,8 @@ function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
     list($last_prefix, $last_test_class) = simpletest_last_test_get($test_id);
     simpletest_log_read($test_id, $last_prefix, $last_test_class);
 
-    drupal_set_message(t('The test run did not successfully finish.'), 'error');
-    drupal_set_message(t('Use the <em>Clean environment</em> button to clean-up temporary files and tables.'), 'warning');
+    \Drupal::messenger()->addError(t('The test run did not successfully finish.'));
+    \Drupal::messenger()->addWarning(t('Use the <em>Clean environment</em> button to clean-up temporary files and tables.'));
   }
   \Drupal::moduleHandler()->invokeAll('test_group_finished');
 }
@@ -658,10 +658,10 @@ function simpletest_clean_environment() {
   simpletest_clean_temporary_directories();
   if (\Drupal::config('simpletest.settings')->get('clear_results')) {
     $count = simpletest_clean_results_table();
-    drupal_set_message(\Drupal::translation()->formatPlural($count, 'Removed 1 test result.', 'Removed @count test results.'));
+    \Drupal::messenger()->addStatus(\Drupal::translation()->formatPlural($count, 'Removed 1 test result.', 'Removed @count test results.'));
   }
   else {
-    drupal_set_message(t('Clear results is disabled and the test results table will not be cleared.'), 'warning');
+    \Drupal::messenger()->addWarning(t('Clear results is disabled and the test results table will not be cleared.'), 'warning');
   }
 }
 
@@ -681,10 +681,10 @@ function simpletest_clean_database() {
   }
 
   if ($count > 0) {
-    drupal_set_message(\Drupal::translation()->formatPlural($count, 'Removed 1 leftover table.', 'Removed @count leftover tables.'));
+    \Drupal::messenger()->addStatus(\Drupal::translation()->formatPlural($count, 'Removed 1 leftover table.', 'Removed @count leftover tables.'));
   }
   else {
-    drupal_set_message(t('No leftover tables to remove.'));
+    \Drupal::messenger()->addStatus(t('No leftover tables to remove.'));
   }
 }
 
@@ -707,10 +707,10 @@ function simpletest_clean_temporary_directories() {
   }
 
   if ($count > 0) {
-    drupal_set_message(\Drupal::translation()->formatPlural($count, 'Removed 1 temporary directory.', 'Removed @count temporary directories.'));
+    \Drupal::messenger()->addStatus(\Drupal::translation()->formatPlural($count, 'Removed 1 temporary directory.', 'Removed @count temporary directories.'));
   }
   else {
-    drupal_set_message(t('No temporary directories to remove.'));
+    \Drupal::messenger()->addStatus(t('No temporary directories to remove.'));
   }
 }
 
diff --git a/core/modules/simpletest/src/Form/SimpletestResultsForm.php b/core/modules/simpletest/src/Form/SimpletestResultsForm.php
index 55a9ca4e87ba..f24727c6f3f5 100644
--- a/core/modules/simpletest/src/Form/SimpletestResultsForm.php
+++ b/core/modules/simpletest/src/Form/SimpletestResultsForm.php
@@ -112,7 +112,7 @@ public function buildForm(array $form, FormStateInterface $form_state, $test_id
     // performed.
     $results = [];
     if (is_numeric($test_id) && !$results = $this->getResults($test_id)) {
-      drupal_set_message($this->t('No test results to display.'), 'error');
+      $this->messenger()->addError($this->t('No test results to display.'));
       return new RedirectResponse($this->url('simpletest.test_form', [], ['absolute' => TRUE]));
     }
 
diff --git a/core/modules/simpletest/src/TestBase.php b/core/modules/simpletest/src/TestBase.php
index 260d1a34af17..ffa6fa58112f 100644
--- a/core/modules/simpletest/src/TestBase.php
+++ b/core/modules/simpletest/src/TestBase.php
@@ -985,7 +985,7 @@ public function run(array $methods = []) {
 
     TestServiceProvider::$currentTest = NULL;
     // Clear out the error messages and restore error handler.
-    drupal_get_messages();
+    \Drupal::messenger()->deleteAll();
     restore_error_handler();
   }
 
diff --git a/core/modules/system/src/Controller/DbUpdateController.php b/core/modules/system/src/Controller/DbUpdateController.php
index 9e0a374a4a86..214e28dd9577 100644
--- a/core/modules/system/src/Controller/DbUpdateController.php
+++ b/core/modules/system/src/Controller/DbUpdateController.php
@@ -335,11 +335,11 @@ protected function selection(Request $request) {
 
     // Warn the user if any updates were incompatible.
     if ($incompatible_updates_exist) {
-      drupal_set_message($this->t('Some of the pending updates cannot be applied because their dependencies were not met.'), 'warning');
+      $this->messenger()->addWarning($this->t('Some of the pending updates cannot be applied because their dependencies were not met.'));
     }
 
     if (empty($count)) {
-      drupal_set_message($this->t('No pending updates.'));
+      $this->messenger()->addStatus($this->t('No pending updates.'));
       unset($build);
       $build['links'] = [
         '#theme' => 'links',
diff --git a/core/modules/system/src/Controller/SystemController.php b/core/modules/system/src/Controller/SystemController.php
index 4af1dcb856f4..42b50d0691c3 100644
--- a/core/modules/system/src/Controller/SystemController.php
+++ b/core/modules/system/src/Controller/SystemController.php
@@ -100,7 +100,7 @@ public static function create(ContainerInterface $container) {
   public function overview($link_id) {
     // Check for status report errors.
     if ($this->systemManager->checkRequirements() && $this->currentUser()->hasPermission('administer site configuration')) {
-      drupal_set_message($this->t('One or more problems were detected with your Drupal installation. Check the <a href=":status">status report</a> for more information.', [':status' => $this->url('system.status')]), 'error');
+      $this->messenger()->addError($this->t('One or more problems were detected with your Drupal installation. Check the <a href=":status">status report</a> for more information.', [':status' => $this->url('system.status')]));
     }
     // Load all menu links below it.
     $parameters = new MenuTreeParameters();
diff --git a/core/modules/system/src/Controller/ThemeController.php b/core/modules/system/src/Controller/ThemeController.php
index 9160085bee64..31be59ed1a43 100644
--- a/core/modules/system/src/Controller/ThemeController.php
+++ b/core/modules/system/src/Controller/ThemeController.php
@@ -71,15 +71,15 @@ public function uninstall(Request $request) {
       if (!empty($themes[$theme])) {
         // Do not uninstall the default or admin theme.
         if ($theme === $config->get('default') || $theme === $config->get('admin')) {
-          drupal_set_message($this->t('%theme is the default theme and cannot be uninstalled.', ['%theme' => $themes[$theme]->info['name']]), 'error');
+          $this->messenger()->addError($this->t('%theme is the default theme and cannot be uninstalled.', ['%theme' => $themes[$theme]->info['name']]));
         }
         else {
           $this->themeHandler->uninstall([$theme]);
-          drupal_set_message($this->t('The %theme theme has been uninstalled.', ['%theme' => $themes[$theme]->info['name']]));
+          $this->messenger()->addStatus($this->t('The %theme theme has been uninstalled.', ['%theme' => $themes[$theme]->info['name']]));
         }
       }
       else {
-        drupal_set_message($this->t('The %theme theme was not found.', ['%theme' => $theme]), 'error');
+        $this->messenger()->addError($this->t('The %theme theme was not found.', ['%theme' => $theme]));
       }
 
       return $this->redirect('system.themes_page');
@@ -108,15 +108,15 @@ public function install(Request $request) {
       try {
         if ($this->themeHandler->install([$theme])) {
           $themes = $this->themeHandler->listInfo();
-          drupal_set_message($this->t('The %theme theme has been installed.', ['%theme' => $themes[$theme]->info['name']]));
+          $this->messenger()->addStatus($this->t('The %theme theme has been installed.', ['%theme' => $themes[$theme]->info['name']]));
         }
         else {
-          drupal_set_message($this->t('The %theme theme was not found.', ['%theme' => $theme]), 'error');
+          $this->messenger()->addError($this->t('The %theme theme was not found.', ['%theme' => $theme]));
         }
       }
       catch (PreExistingConfigException $e) {
         $config_objects = $e->flattenConfigObjects($e->getConfigObjects());
-        drupal_set_message(
+        $this->messenger()->addError(
           $this->formatPlural(
             count($config_objects),
             'Unable to install @extension, %config_names already exists in active configuration.',
@@ -124,12 +124,11 @@ public function install(Request $request) {
             [
               '%config_names' => implode(', ', $config_objects),
               '@extension' => $theme,
-            ]),
-          'error'
+            ])
         );
       }
       catch (UnmetDependenciesException $e) {
-        drupal_set_message($e->getTranslatedMessage($this->getStringTranslation(), $theme), 'error');
+        $this->messenger()->addError($e->getTranslatedMessage($this->getStringTranslation(), $theme));
       }
 
       return $this->redirect('system.themes_page');
@@ -171,17 +170,18 @@ public function setDefaultTheme(Request $request) {
         // theme.
         $admin_theme = $config->get('admin');
         if ($admin_theme != 0 && $admin_theme != $theme) {
-          drupal_set_message($this->t('Please note that the administration theme is still set to the %admin_theme theme; consequently, the theme on this page remains unchanged. All non-administrative sections of the site, however, will show the selected %selected_theme theme by default.', [
-            '%admin_theme' => $themes[$admin_theme]->info['name'],
-            '%selected_theme' => $themes[$theme]->info['name'],
-          ]));
+          $this->messenger()
+            ->addStatus($this->t('Please note that the administration theme is still set to the %admin_theme theme; consequently, the theme on this page remains unchanged. All non-administrative sections of the site, however, will show the selected %selected_theme theme by default.', [
+              '%admin_theme' => $themes[$admin_theme]->info['name'],
+              '%selected_theme' => $themes[$theme]->info['name'],
+            ]));
         }
         else {
-          drupal_set_message($this->t('%theme is now the default theme.', ['%theme' => $themes[$theme]->info['name']]));
+          $this->messenger()->addStatus($this->t('%theme is now the default theme.', ['%theme' => $themes[$theme]->info['name']]));
         }
       }
       else {
-        drupal_set_message($this->t('The %theme theme was not found.', ['%theme' => $theme]), 'error');
+        $this->messenger()->addError($this->t('The %theme theme was not found.', ['%theme' => $theme]));
       }
 
       return $this->redirect('system.themes_page');
diff --git a/core/modules/system/src/CronController.php b/core/modules/system/src/CronController.php
index ec1156955f3b..915a0c887eb1 100644
--- a/core/modules/system/src/CronController.php
+++ b/core/modules/system/src/CronController.php
@@ -58,10 +58,10 @@ public function run() {
    */
   public function runManually() {
     if ($this->cron->run()) {
-      drupal_set_message($this->t('Cron ran successfully.'));
+      $this->messenger()->addStatus($this->t('Cron ran successfully.'));
     }
     else {
-      drupal_set_message($this->t('Cron run failed.'), 'error');
+      $this->messenger()->addError($this->t('Cron run failed.'));
     }
 
     return $this->redirect('system.status');
diff --git a/core/modules/system/src/Form/CronForm.php b/core/modules/system/src/Form/CronForm.php
index 228dc0b4a4b9..a585aa57cb7c 100644
--- a/core/modules/system/src/Form/CronForm.php
+++ b/core/modules/system/src/Form/CronForm.php
@@ -155,7 +155,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     $this->config('system.cron')
       ->set('logging', $form_state->getValue('logging'))
       ->save();
-    drupal_set_message(t('The configuration options have been saved.'));
+    $this->messenger()->addStatus(t('The configuration options have been saved.'));
   }
 
   /**
@@ -163,10 +163,10 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
    */
   public function runCron(array &$form, FormStateInterface $form_state) {
     if ($this->cron->run()) {
-      drupal_set_message($this->t('Cron ran successfully.'));
+      $this->messenger()->addStatus($this->t('Cron ran successfully.'));
     }
     else {
-      drupal_set_message($this->t('Cron run failed.'), 'error');
+      $this->messenger()->addError($this->t('Cron run failed.'));
     }
   }
 
diff --git a/core/modules/system/src/Form/DateFormatFormBase.php b/core/modules/system/src/Form/DateFormatFormBase.php
index ed6714fc6833..9e92a70c4420 100644
--- a/core/modules/system/src/Form/DateFormatFormBase.php
+++ b/core/modules/system/src/Form/DateFormatFormBase.php
@@ -129,7 +129,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) {
     $pattern = trim($form_state->getValue('date_format_pattern'));
     foreach ($this->dateFormatStorage->loadMultiple() as $format) {
       if ($format->getPattern() == $pattern && ($format->id() == $this->entity->id())) {
-        drupal_set_message(t('The existing format/name combination has not been altered.'));
+        $this->messenger()->addStatus($this->t('The existing format/name combination has not been altered.'));
         continue;
       }
     }
@@ -149,10 +149,10 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
   public function save(array $form, FormStateInterface $form_state) {
     $status = $this->entity->save();
     if ($status == SAVED_UPDATED) {
-      drupal_set_message(t('Custom date format updated.'));
+      $this->messenger()->addStatus($this->t('Custom date format updated.'));
     }
     else {
-      drupal_set_message(t('Custom date format added.'));
+      $this->messenger()->addStatus($this->t('Custom date format added.'));
     }
     $form_state->setRedirectUrl($this->entity->urlInfo('collection'));
   }
diff --git a/core/modules/system/src/Form/ModulesListConfirmForm.php b/core/modules/system/src/Form/ModulesListConfirmForm.php
index 912a4327fd98..834b436345b9 100644
--- a/core/modules/system/src/Form/ModulesListConfirmForm.php
+++ b/core/modules/system/src/Form/ModulesListConfirmForm.php
@@ -174,29 +174,27 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       }
       catch (PreExistingConfigException $e) {
         $config_objects = $e->flattenConfigObjects($e->getConfigObjects());
-        drupal_set_message(
+        $this->messenger()->addError(
           $this->formatPlural(
             count($config_objects),
             'Unable to install @extension, %config_names already exists in active configuration.',
             'Unable to install @extension, %config_names already exist in active configuration.',
             [
               '%config_names' => implode(', ', $config_objects),
-              '@extension' => $this->modules['install'][$e->getExtension()]
-            ]),
-          'error'
+              '@extension' => $this->modules['install'][$e->getExtension()],
+            ])
         );
         return;
       }
       catch (UnmetDependenciesException $e) {
-        drupal_set_message(
-          $e->getTranslatedMessage($this->getStringTranslation(), $this->modules['install'][$e->getExtension()]),
-          'error'
+        $this->messenger()->addError(
+          $e->getTranslatedMessage($this->getStringTranslation(), $this->modules['install'][$e->getExtension()])
         );
         return;
       }
 
       $module_names = array_values($this->modules['install']);
-      drupal_set_message($this->formatPlural(count($module_names), 'Module %name has been enabled.', '@count modules have been enabled: %names.', [
+      $this->messenger()->addStatus($this->formatPlural(count($module_names), 'Module %name has been enabled.', '@count modules have been enabled: %names.', [
         '%name' => $module_names[0],
         '%names' => implode(', ', $module_names),
       ]));
diff --git a/core/modules/system/src/Form/ModulesListExperimentalConfirmForm.php b/core/modules/system/src/Form/ModulesListExperimentalConfirmForm.php
index 5586ce70ba7e..2f410f278557 100644
--- a/core/modules/system/src/Form/ModulesListExperimentalConfirmForm.php
+++ b/core/modules/system/src/Form/ModulesListExperimentalConfirmForm.php
@@ -27,7 +27,7 @@ public function getFormId() {
    * {@inheritdoc}
    */
   protected function buildMessageList() {
-    drupal_set_message($this->t('<a href=":url">Experimental modules</a> are provided for testing purposes only. Use at your own risk.', [':url' => 'https://www.drupal.org/core/experimental']), 'warning');
+    $this->messenger()->addWarning($this->t('<a href=":url">Experimental modules</a> are provided for testing purposes only. Use at your own risk.', [':url' => 'https://www.drupal.org/core/experimental']));
 
     $items = parent::buildMessageList();
     // Add the list of experimental modules after any other messages.
diff --git a/core/modules/system/src/Form/ModulesListForm.php b/core/modules/system/src/Form/ModulesListForm.php
index 3ff6c3d09d35..3c6f2a899145 100644
--- a/core/modules/system/src/Form/ModulesListForm.php
+++ b/core/modules/system/src/Form/ModulesListForm.php
@@ -450,30 +450,28 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       try {
         $this->moduleInstaller->install(array_keys($modules['install']));
         $module_names = array_values($modules['install']);
-        drupal_set_message($this->formatPlural(count($module_names), 'Module %name has been enabled.', '@count modules have been enabled: %names.', [
+        $this->messenger()->addStatus($this->formatPlural(count($module_names), 'Module %name has been enabled.', '@count modules have been enabled: %names.', [
           '%name' => $module_names[0],
           '%names' => implode(', ', $module_names),
         ]));
       }
       catch (PreExistingConfigException $e) {
         $config_objects = $e->flattenConfigObjects($e->getConfigObjects());
-        drupal_set_message(
+        $this->messenger()->addError(
           $this->formatPlural(
             count($config_objects),
             'Unable to install @extension, %config_names already exists in active configuration.',
             'Unable to install @extension, %config_names already exist in active configuration.',
             [
               '%config_names' => implode(', ', $config_objects),
-              '@extension' => $modules['install'][$e->getExtension()]
-            ]),
-          'error'
+              '@extension' => $modules['install'][$e->getExtension()],
+            ])
         );
         return;
       }
       catch (UnmetDependenciesException $e) {
-        drupal_set_message(
-          $e->getTranslatedMessage($this->getStringTranslation(), $modules['install'][$e->getExtension()]),
-          'error'
+        $this->messenger()->addError(
+          $e->getTranslatedMessage($this->getStringTranslation(), $modules['install'][$e->getExtension()])
         );
         return;
       }
diff --git a/core/modules/system/src/Form/ModulesUninstallConfirmForm.php b/core/modules/system/src/Form/ModulesUninstallConfirmForm.php
index f55f0d69ec5a..a9783a908fca 100644
--- a/core/modules/system/src/Form/ModulesUninstallConfirmForm.php
+++ b/core/modules/system/src/Form/ModulesUninstallConfirmForm.php
@@ -131,7 +131,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
 
     // Prevent this page from showing when the module list is empty.
     if (empty($this->modules)) {
-      drupal_set_message($this->t('The selected modules could not be uninstalled, either due to a website problem or due to the uninstall confirmation form timing out. Please try again.'), 'error');
+      $this->messenger()->addError($this->t('The selected modules could not be uninstalled, either due to a website problem or due to the uninstall confirmation form timing out. Please try again.'));
       return $this->redirect('system.modules_uninstall');
     }
 
@@ -161,7 +161,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     // Uninstall the modules.
     $this->moduleInstaller->uninstall($this->modules);
 
-    drupal_set_message($this->t('The selected modules have been uninstalled.'));
+    $this->messenger()->addStatus($this->t('The selected modules have been uninstalled.'));
     $form_state->setRedirectUrl($this->getCancelUrl());
   }
 
diff --git a/core/modules/system/src/Form/PerformanceForm.php b/core/modules/system/src/Form/PerformanceForm.php
index 0e5c7840842e..9d19b7599c35 100644
--- a/core/modules/system/src/Form/PerformanceForm.php
+++ b/core/modules/system/src/Form/PerformanceForm.php
@@ -190,7 +190,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
    */
   public function submitCacheClear(array &$form, FormStateInterface $form_state) {
     drupal_flush_all_caches();
-    drupal_set_message(t('Caches cleared.'));
+    $this->messenger()->addStatus($this->t('Caches cleared.'));
   }
 
 }
diff --git a/core/modules/system/src/Form/PrepareModulesEntityUninstallForm.php b/core/modules/system/src/Form/PrepareModulesEntityUninstallForm.php
index 079e574ed8ac..8641cbc3eed1 100644
--- a/core/modules/system/src/Form/PrepareModulesEntityUninstallForm.php
+++ b/core/modules/system/src/Form/PrepareModulesEntityUninstallForm.php
@@ -250,7 +250,7 @@ public static function deleteContentEntities($entity_type_id, &$context) {
    */
   public static function moduleBatchFinished($success, $results, $operations) {
     $entity_type_plural = \Drupal::entityTypeManager()->getDefinition($results['entity_type_id'])->getPluralLabel();
-    drupal_set_message(t('All @entity_type_plural have been deleted.', ['@entity_type_plural' => $entity_type_plural]));
+    \Drupal::messenger()->addStatus(t('All @entity_type_plural have been deleted.', ['@entity_type_plural' => $entity_type_plural]));
 
     return new RedirectResponse(Url::fromRoute('system.modules_uninstall')->setAbsolute()->toString());
   }
diff --git a/core/modules/system/src/Plugin/Block/SystemMessagesBlock.php b/core/modules/system/src/Plugin/Block/SystemMessagesBlock.php
index 0b6638f43bef..99901957e761 100644
--- a/core/modules/system/src/Plugin/Block/SystemMessagesBlock.php
+++ b/core/modules/system/src/Plugin/Block/SystemMessagesBlock.php
@@ -9,7 +9,7 @@
 /**
  * Provides a block to display the messages.
  *
- * @see drupal_set_message()
+ * @see @see \Drupal\Core\Messenger\MessengerInterface
  *
  * @Block(
  *   id = "system_messages_block",
diff --git a/core/modules/system/src/Tests/Form/ElementsTableSelectTest.php b/core/modules/system/src/Tests/Form/ElementsTableSelectTest.php
index d335518a9ff5..9cbda92cf6da 100644
--- a/core/modules/system/src/Tests/Form/ElementsTableSelectTest.php
+++ b/core/modules/system/src/Tests/Form/ElementsTableSelectTest.php
@@ -248,7 +248,7 @@ private function formSubmitHelper($form, $edit) {
     $errors = $form_state->getErrors();
 
     // Clear errors and messages.
-    drupal_get_messages();
+    \Drupal::messenger()->deleteAll();
     $form_state->clearErrors();
 
     // Return the processed form together with form_state and errors
diff --git a/core/modules/system/src/Tests/Theme/ThemeSuggestionsAlterTest.php b/core/modules/system/src/Tests/Theme/ThemeSuggestionsAlterTest.php
index c01a94fec259..2277adb342b4 100644
--- a/core/modules/system/src/Tests/Theme/ThemeSuggestionsAlterTest.php
+++ b/core/modules/system/src/Tests/Theme/ThemeSuggestionsAlterTest.php
@@ -166,7 +166,7 @@ public function testExecutionOrder() {
     $this->resetAll();
 
     // Send two requests so that we get all the messages we've set via
-    // drupal_set_message().
+    // \Drupal\Core\Messenger\MessengerInterface::addStatus().
     $this->drupalGet('theme-test/suggestion-alter');
     // Ensure that the order is first by extension, then for a given extension,
     // the hook-specific one after the generic one.
diff --git a/core/modules/system/system.module b/core/modules/system/system.module
index bb82d4b19f3f..d08e1016c816 100644
--- a/core/modules/system/system.module
+++ b/core/modules/system/system.module
@@ -834,7 +834,13 @@ function system_user_login(UserInterface $account) {
   $config = \Drupal::config('system.date');
   // If the user has a NULL time zone, notify them to set a time zone.
   if (!$account->getTimezone() && $config->get('timezone.user.configurable') && $config->get('timezone.user.warn')) {
-    drupal_set_message(t('Configure your <a href=":user-edit">account time zone setting</a>.', [':user-edit' => $account->url('edit-form', ['query' => \Drupal::destination()->getAsArray(), 'fragment' => 'edit-timezone'])]));
+    \Drupal::messenger()
+      ->addStatus(t('Configure your <a href=":user-edit">account time zone setting</a>.', [
+        ':user-edit' => $account->url('edit-form', [
+          'query' => \Drupal::destination()->getAsArray(),
+          'fragment' => 'edit-timezone',
+        ]),
+      ]));
   }
 }
 
@@ -1367,11 +1373,11 @@ function system_retrieve_file($url, $destination = NULL, $managed = FALSE, $repl
     $local = $managed ? file_save_data($data, $path, $replace) : file_unmanaged_save_data($data, $path, $replace);
   }
   catch (RequestException $exception) {
-    drupal_set_message(t('Failed to fetch file due to error "%error"', ['%error' => $exception->getMessage()]), 'error');
+    \Drupal::messenger()->addError(t('Failed to fetch file due to error "%error"', ['%error' => $exception->getMessage()]));
     return FALSE;
   }
   if (!$local) {
-    drupal_set_message(t('@remote could not be saved to @path.', ['@remote' => $url, '@path' => $path]), 'error');
+    \Drupal::messenger()->addError(t('@remote could not be saved to @path.', ['@remote' => $url, '@path' => $path]));
   }
 
   return $local;
diff --git a/core/modules/system/tests/modules/ajax_forms_test/ajax_forms_test.module b/core/modules/system/tests/modules/ajax_forms_test/ajax_forms_test.module
index 262572be9a7d..a93372d06d10 100644
--- a/core/modules/system/tests/modules/ajax_forms_test/ajax_forms_test.module
+++ b/core/modules/system/tests/modules/ajax_forms_test/ajax_forms_test.module
@@ -180,8 +180,8 @@ function ajax_forms_test_advanced_commands_add_css_callback($form, FormStateInte
  * Ajax form callback: Selects the 'drivertext' element of the validation form.
  */
 function ajax_forms_test_validation_form_callback($form, FormStateInterface $form_state) {
-  drupal_set_message("ajax_forms_test_validation_form_callback invoked");
-  drupal_set_message(t("Callback: drivertext=%drivertext, spare_required_field=%spare_required_field", ['%drivertext' => $form_state->getValue('drivertext'), '%spare_required_field' => $form_state->getValue('spare_required_field')]));
+  \Drupal::messenger()->addStatus("ajax_forms_test_validation_form_callback invoked");
+  \Drupal::messenger()->addStatus(t("Callback: drivertext=%drivertext, spare_required_field=%spare_required_field", ['%drivertext' => $form_state->getValue('drivertext'), '%spare_required_field' => $form_state->getValue('spare_required_field')]));
   return ['#markup' => '<div id="message_area">ajax_forms_test_validation_form_callback at ' . date('c') . '</div>'];
 }
 
@@ -189,8 +189,8 @@ function ajax_forms_test_validation_form_callback($form, FormStateInterface $for
  * Ajax form callback: Selects the 'drivernumber' element of the validation form.
  */
 function ajax_forms_test_validation_number_form_callback($form, FormStateInterface $form_state) {
-  drupal_set_message("ajax_forms_test_validation_number_form_callback invoked");
-  drupal_set_message(t("Callback: drivernumber=%drivernumber, spare_required_field=%spare_required_field", ['%drivernumber' => $form_state->getValue('drivernumber'), '%spare_required_field' => $form_state->getValue('spare_required_field')]));
+  \Drupal::messenger()->addStatus("ajax_forms_test_validation_number_form_callback invoked");
+  \Drupal::messenger()->addStatus(t("Callback: drivernumber=%drivernumber, spare_required_field=%spare_required_field", ['%drivernumber' => $form_state->getValue('drivernumber'), '%spare_required_field' => $form_state->getValue('spare_required_field')]));
   return ['#markup' => '<div id="message_area_number">ajax_forms_test_validation_number_form_callback at ' . date('c') . '</div>'];
 }
 
diff --git a/core/modules/system/tests/modules/ajax_forms_test/src/Form/AjaxFormsTestValidationForm.php b/core/modules/system/tests/modules/ajax_forms_test/src/Form/AjaxFormsTestValidationForm.php
index d908e3809cdf..ef6ddaf73653 100644
--- a/core/modules/system/tests/modules/ajax_forms_test/src/Form/AjaxFormsTestValidationForm.php
+++ b/core/modules/system/tests/modules/ajax_forms_test/src/Form/AjaxFormsTestValidationForm.php
@@ -67,7 +67,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message($this->t("Validation form submitted"));
+    $this->messenger()->addStatus($this->t("Validation form submitted"));
   }
 
 }
diff --git a/core/modules/system/tests/modules/ajax_forms_test/src/Plugin/Block/AjaxFormBlock.php b/core/modules/system/tests/modules/ajax_forms_test/src/Plugin/Block/AjaxFormBlock.php
index aa50cc4658c0..65e1372d999f 100644
--- a/core/modules/system/tests/modules/ajax_forms_test/src/Plugin/Block/AjaxFormBlock.php
+++ b/core/modules/system/tests/modules/ajax_forms_test/src/Plugin/Block/AjaxFormBlock.php
@@ -6,6 +6,7 @@
 use Drupal\Core\Form\FormBuilderInterface;
 use Drupal\Core\Form\FormInterface;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
 use Symfony\Component\DependencyInjection\ContainerInterface;
 
@@ -27,6 +28,13 @@ class AjaxFormBlock extends BlockBase implements FormInterface, ContainerFactory
    */
   protected $formBuilder;
 
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
   /**
    * Constructs a new AjaxFormBlock.
    *
@@ -38,10 +46,13 @@ class AjaxFormBlock extends BlockBase implements FormInterface, ContainerFactory
    *   The plugin implementation definition.
    * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
    *   The form builder.
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   The messenger.
    */
-  public function __construct(array $configuration, $plugin_id, $plugin_definition, FormBuilderInterface $form_builder) {
+  public function __construct(array $configuration, $plugin_id, $plugin_definition, FormBuilderInterface $form_builder, MessengerInterface $messenger) {
     parent::__construct($configuration, $plugin_id, $plugin_definition);
     $this->formBuilder = $form_builder;
+    $this->messenger = $messenger;
   }
 
   /**
@@ -52,7 +63,8 @@ public static function create(ContainerInterface $container, array $configuratio
       $configuration,
       $plugin_id,
       $plugin_definition,
-      $container->get('form_builder')
+      $container->get('form_builder'),
+      $container->get('messenger')
     );
   }
 
@@ -129,7 +141,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message('Submission successful.');
+    $this->messenger->addStatus('Submission successful.');
   }
 
 }
diff --git a/core/modules/system/tests/modules/batch_test/batch_test.callbacks.inc b/core/modules/system/tests/modules/batch_test/batch_test.callbacks.inc
index 9116c85fed7a..eb1832185e83 100644
--- a/core/modules/system/tests/modules/batch_test/batch_test.callbacks.inc
+++ b/core/modules/system/tests/modules/batch_test/batch_test.callbacks.inc
@@ -116,7 +116,7 @@ function _batch_test_finished_helper($batch_id, $success, $results, $operations)
     ],
   ];
 
-  drupal_set_message(\Drupal::service('renderer')->renderPlain($error_message));
+  \Drupal::messenger()->addStatus(\Drupal::service('renderer')->renderPlain($error_message));
 }
 
 /**
diff --git a/core/modules/system/tests/modules/condition_test/src/FormController.php b/core/modules/system/tests/modules/condition_test/src/FormController.php
index da475ae0c4e9..19dc9505bd28 100644
--- a/core/modules/system/tests/modules/condition_test/src/FormController.php
+++ b/core/modules/system/tests/modules/condition_test/src/FormController.php
@@ -60,13 +60,13 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     $this->condition->submitConfigurationForm($form, $form_state);
     $config = $this->condition->getConfig();
     foreach ($config['bundles'] as $bundle) {
-      drupal_set_message('Bundle: ' . $bundle);
+      \Drupal::messenger()->addStatus('Bundle: ' . $bundle);
     }
 
     $article = Node::load(1);
     $this->condition->setContextValue('node', $article);
     if ($this->condition->execute()) {
-      drupal_set_message(t('Executed successfully.'));
+      \Drupal::messenger()->addStatus(t('Executed successfully.'));
     }
   }
 
diff --git a/core/modules/system/tests/modules/entity_test/src/EntityTestForm.php b/core/modules/system/tests/modules/entity_test/src/EntityTestForm.php
index 75ff8ad9bf5d..d471d6058200 100644
--- a/core/modules/system/tests/modules/entity_test/src/EntityTestForm.php
+++ b/core/modules/system/tests/modules/entity_test/src/EntityTestForm.php
@@ -65,7 +65,7 @@ public function save(array $form, FormStateInterface $form_state) {
       else {
         $message = t('%entity_type @id has been updated.', ['@id' => $entity->id(), '%entity_type' => $entity->getEntityTypeId()]);
       }
-      drupal_set_message($message);
+      $this->messenger()->addStatus($message);
 
       if ($entity->id()) {
         $entity_type = $entity->getEntityTypeId();
@@ -76,7 +76,7 @@ public function save(array $form, FormStateInterface $form_state) {
       }
       else {
         // Error on save.
-        drupal_set_message(t('The entity could not be saved.'), 'error');
+        $this->messenger()->addError($this->t('The entity could not be saved.'));
         $form_state->setRebuild();
       }
     }
diff --git a/core/modules/system/tests/modules/form_test/form_test.module b/core/modules/system/tests/modules/form_test/form_test.module
index e3a5e3f28122..14e011877a7d 100644
--- a/core/modules/system/tests/modules/form_test/form_test.module
+++ b/core/modules/system/tests/modules/form_test/form_test.module
@@ -11,7 +11,7 @@
  * Implements hook_form_FORM_ID_alter() on behalf of block.module.
  */
 function block_form_form_test_alter_form_alter(&$form, FormStateInterface $form_state) {
-  drupal_set_message('block_form_form_test_alter_form_alter() executed.');
+  \Drupal::messenger()->addStatus('block_form_form_test_alter_form_alter() executed.');
 }
 
 /**
@@ -19,7 +19,7 @@ function block_form_form_test_alter_form_alter(&$form, FormStateInterface $form_
  */
 function form_test_form_alter(&$form, FormStateInterface $form_state, $form_id) {
   if ($form_id == 'form_test_alter_form') {
-    drupal_set_message('form_test_form_alter() executed.');
+    \Drupal::messenger()->addStatus('form_test_form_alter() executed.');
   }
 }
 
@@ -27,14 +27,14 @@ function form_test_form_alter(&$form, FormStateInterface $form_state, $form_id)
  * Implements hook_form_FORM_ID_alter().
  */
 function form_test_form_form_test_alter_form_alter(&$form, FormStateInterface $form_state) {
-  drupal_set_message('form_test_form_form_test_alter_form_alter() executed.');
+  \Drupal::messenger()->addStatus('form_test_form_form_test_alter_form_alter() executed.');
 }
 
 /**
  * Implements hook_form_FORM_ID_alter() on behalf of system.module.
  */
 function system_form_form_test_alter_form_alter(&$form, FormStateInterface $form_state) {
-  drupal_set_message('system_form_form_test_alter_form_alter() executed.');
+  \Drupal::messenger()->addStatus('system_form_form_test_alter_form_alter() executed.');
 }
 
 /**
@@ -90,7 +90,7 @@ function form_test_form_user_register_form_alter(&$form, FormStateInterface $for
  * Submit callback that just lets the form rebuild.
  */
 function form_test_user_register_form_rebuild($form, FormStateInterface $form_state) {
-  drupal_set_message('Form rebuilt.');
+  \Drupal::messenger()->addStatus('Form rebuilt.');
   $form_state->setRebuild();
 }
 
diff --git a/core/modules/system/tests/modules/form_test/src/Callbacks.php b/core/modules/system/tests/modules/form_test/src/Callbacks.php
index 0310a37e52f6..4af6f2e7041e 100644
--- a/core/modules/system/tests/modules/form_test/src/Callbacks.php
+++ b/core/modules/system/tests/modules/form_test/src/Callbacks.php
@@ -38,7 +38,7 @@ public function validateName(&$element, FormStateInterface $form_state) {
 
     if ($triggered) {
       // Output the element's value from $form_state.
-      drupal_set_message(t('@label value: @value', ['@label' => $element['#title'], '@value' => $form_state->getValue('name')]));
+      \Drupal::messenger()->addStatus(t('@label value: @value', ['@label' => $element['#title'], '@value' => $form_state->getValue('name')]));
 
       // Trigger a form validation error to see our changes.
       $form_state->setErrorByName('');
diff --git a/core/modules/system/tests/modules/form_test/src/ConfirmFormTestForm.php b/core/modules/system/tests/modules/form_test/src/ConfirmFormTestForm.php
index c5d4cef94d53..089661fe4f5e 100644
--- a/core/modules/system/tests/modules/form_test/src/ConfirmFormTestForm.php
+++ b/core/modules/system/tests/modules/form_test/src/ConfirmFormTestForm.php
@@ -68,7 +68,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message($this->t('The ConfirmFormTestForm::submitForm() method was used for this form.'));
+    $this->messenger()->addStatus($this->t('The ConfirmFormTestForm::submitForm() method was used for this form.'));
     $form_state->setRedirect('<front>');
   }
 
diff --git a/core/modules/system/tests/modules/form_test/src/Form/FormTestClickedButtonForm.php b/core/modules/system/tests/modules/form_test/src/Form/FormTestClickedButtonForm.php
index e95244c478d3..b54770804375 100644
--- a/core/modules/system/tests/modules/form_test/src/Form/FormTestClickedButtonForm.php
+++ b/core/modules/system/tests/modules/form_test/src/Form/FormTestClickedButtonForm.php
@@ -83,10 +83,10 @@ public function buildForm(array $form, FormStateInterface $form_state, $first =
    */
   public function validateForm(array &$form, FormStateInterface $form_state) {
     if ($triggering_element = $form_state->getTriggeringElement()) {
-      drupal_set_message(t('The clicked button is %name.', ['%name' => $triggering_element['#name']]));
+      $this->messenger()->addStatus(t('The clicked button is %name.', ['%name' => $triggering_element['#name']]));
     }
     else {
-      drupal_set_message('There is no clicked button.');
+      $this->messenger()->addStatus('There is no clicked button.');
     }
   }
 
@@ -94,7 +94,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message('Submit handler for form_test_clicked_button executed.');
+    $this->messenger()->addStatus('Submit handler for form_test_clicked_button executed.');
   }
 
 }
diff --git a/core/modules/system/tests/modules/form_test/src/Form/FormTestGetForm.php b/core/modules/system/tests/modules/form_test/src/Form/FormTestGetForm.php
index a032771e9c41..bf9ce60dcf6c 100644
--- a/core/modules/system/tests/modules/form_test/src/Form/FormTestGetForm.php
+++ b/core/modules/system/tests/modules/form_test/src/Form/FormTestGetForm.php
@@ -35,7 +35,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message('The form_test_get_form form has been submitted successfully.');
+    $this->messenger()->addStatus('The form_test_get_form form has been submitted successfully.');
   }
 
 }
diff --git a/core/modules/system/tests/modules/form_test/src/Form/FormTestLimitValidationErrorsForm.php b/core/modules/system/tests/modules/form_test/src/Form/FormTestLimitValidationErrorsForm.php
index 883602217373..8f6531f5c5b3 100644
--- a/core/modules/system/tests/modules/form_test/src/Form/FormTestLimitValidationErrorsForm.php
+++ b/core/modules/system/tests/modules/form_test/src/Form/FormTestLimitValidationErrorsForm.php
@@ -104,7 +104,7 @@ public function partialSubmitForm(array &$form, FormStateInterface $form_state)
     // The title has not been validated, thus its value - in case of the test case
     // an empty string - may not be set.
     if (!$form_state->hasValue('title') && $form_state->hasValue('test')) {
-      drupal_set_message('Only validated values appear in the form values.');
+      $this->messenger()->addStatus('Only validated values appear in the form values.');
     }
   }
 
diff --git a/core/modules/system/tests/modules/form_test/src/Form/FormTestRebuildPreserveValuesForm.php b/core/modules/system/tests/modules/form_test/src/Form/FormTestRebuildPreserveValuesForm.php
index 662de8f7d482..b1054abf0040 100644
--- a/core/modules/system/tests/modules/form_test/src/Form/FormTestRebuildPreserveValuesForm.php
+++ b/core/modules/system/tests/modules/form_test/src/Form/FormTestRebuildPreserveValuesForm.php
@@ -94,7 +94,7 @@ public function addMoreSubmitForm(array &$form, FormStateInterface $form_state)
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
     // Finish the workflow. Do not rebuild.
-    drupal_set_message(t('Form values: %values', ['%values' => var_export($form_state->getValues(), TRUE)]));
+    $this->messenger()->addStatus($this->t('Form values: %values', ['%values' => var_export($form_state->getValues(), TRUE)]));
   }
 
 }
diff --git a/core/modules/system/tests/modules/form_test/src/Form/FormTestStatePersistForm.php b/core/modules/system/tests/modules/form_test/src/Form/FormTestStatePersistForm.php
index af7f51cf8981..5f34bba4d61f 100644
--- a/core/modules/system/tests/modules/form_test/src/Form/FormTestStatePersistForm.php
+++ b/core/modules/system/tests/modules/form_test/src/Form/FormTestStatePersistForm.php
@@ -42,7 +42,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message($form_state->get('value'));
+    $this->messenger()->addStatus($form_state->get('value'));
     $form_state->setRebuild();
   }
 
diff --git a/core/modules/system/tests/modules/form_test/src/Form/FormTestStorageForm.php b/core/modules/system/tests/modules/form_test/src/Form/FormTestStorageForm.php
index f81658d537d7..5cc09b728069 100644
--- a/core/modules/system/tests/modules/form_test/src/Form/FormTestStorageForm.php
+++ b/core/modules/system/tests/modules/form_test/src/Form/FormTestStorageForm.php
@@ -50,7 +50,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
     }
     // Count how often the form is constructed.
     $_SESSION['constructions']++;
-    drupal_set_message("Form constructions: " . $_SESSION['constructions']);
+    $this->messenger()->addStatus("Form constructions: " . $_SESSION['constructions']);
 
     $form['title'] = [
       '#type' => 'textfield',
@@ -136,10 +136,10 @@ public function continueSubmitForm(array &$form, FormStateInterface $form_state)
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message("Title: " . Html::escape($form_state->getValue('title')));
-    drupal_set_message("Form constructions: " . $_SESSION['constructions']);
+    $this->messenger()->addStatus("Title: " . Html::escape($form_state->getValue('title')));
+    $this->messenger()->addStatus("Form constructions: " . $_SESSION['constructions']);
     if ($form_state->has(['thing', 'changed'])) {
-      drupal_set_message("The thing has been changed.");
+      $this->messenger()->addStatus("The thing has been changed.");
     }
     $form_state->setRedirect('<front>');
   }
diff --git a/core/modules/system/tests/modules/form_test/src/Form/FormTestTableSelectMultipleFalseForm.php b/core/modules/system/tests/modules/form_test/src/Form/FormTestTableSelectMultipleFalseForm.php
index d79b235e0f29..31db2ebf385b 100644
--- a/core/modules/system/tests/modules/form_test/src/Form/FormTestTableSelectMultipleFalseForm.php
+++ b/core/modules/system/tests/modules/form_test/src/Form/FormTestTableSelectMultipleFalseForm.php
@@ -29,7 +29,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message(t('Submitted: @value', ['@value' => $form_state->getValue('tableselect')]));
+    $this->messenger()->addStatus($this->t('Submitted: @value', ['@value' => $form_state->getValue('tableselect')]));
   }
 
 }
diff --git a/core/modules/system/tests/modules/form_test/src/Form/FormTestTableSelectMultipleTrueForm.php b/core/modules/system/tests/modules/form_test/src/Form/FormTestTableSelectMultipleTrueForm.php
index 1d46d7cc6596..abfa38035933 100644
--- a/core/modules/system/tests/modules/form_test/src/Form/FormTestTableSelectMultipleTrueForm.php
+++ b/core/modules/system/tests/modules/form_test/src/Form/FormTestTableSelectMultipleTrueForm.php
@@ -31,7 +31,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
   public function submitForm(array &$form, FormStateInterface $form_state) {
     $selected = $form_state->getValue('tableselect');
     foreach ($selected as $key => $value) {
-      drupal_set_message(t('Submitted: @key = @value', ['@key' => $key, '@value' => $value]));
+      $this->messenger()->addStatus($this->t('Submitted: @key = @value', ['@key' => $key, '@value' => $value]));
     }
   }
 
diff --git a/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateForm.php b/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateForm.php
index 7123aceef1a8..a662e8505243 100644
--- a/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateForm.php
+++ b/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateForm.php
@@ -59,7 +59,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) {
       // Alter the submitted value in $form_state.
       $form_state->setValueForElement($form['name'], 'value changed by setValueForElement() in #validate');
       // Output the element's value from $form_state.
-      drupal_set_message(t('@label value: @value', ['@label' => $form['name']['#title'], '@value' => $form_state->getValue('name')]));
+      $this->messenger()->addStatus($this->t('@label value: @value', ['@label' => $form['name']['#title'], '@value' => $form_state->getValue('name')]));
 
       // Trigger a form validation error to see our changes.
       $form_state->setErrorByName('');
diff --git a/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateNoToken.php b/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateNoToken.php
index c4b568edd085..7a5e7ff03b55 100644
--- a/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateNoToken.php
+++ b/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateNoToken.php
@@ -35,7 +35,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message('The form_test_validate_no_token form has been submitted successfully.');
+    $this->messenger()->addStatus('The form_test_validate_no_token form has been submitted successfully.');
   }
 
 }
diff --git a/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateRequiredForm.php b/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateRequiredForm.php
index 13aec600abe1..91be7b1e7fca 100644
--- a/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateRequiredForm.php
+++ b/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateRequiredForm.php
@@ -84,7 +84,7 @@ public function elementValidateRequired($element, FormStateInterface $form_state
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message('The form_test_validate_required_form form was submitted successfully.');
+    $this->messenger()->addStatus('The form_test_validate_required_form form was submitted successfully.');
   }
 
 }
diff --git a/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateRequiredNoTitleForm.php b/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateRequiredNoTitleForm.php
index 1829ab25662b..fd1c2512313f 100644
--- a/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateRequiredNoTitleForm.php
+++ b/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateRequiredNoTitleForm.php
@@ -36,7 +36,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message('The form_test_validate_required_form_no_title form was submitted successfully.');
+    $this->messenger()->addStatus('The form_test_validate_required_form_no_title form was submitted successfully.');
   }
 
 }
diff --git a/core/modules/system/tests/modules/form_test/src/Form/FormTestVerticalTabsAccessForm.php b/core/modules/system/tests/modules/form_test/src/Form/FormTestVerticalTabsAccessForm.php
index 1b343fccc932..c2d062a64f70 100644
--- a/core/modules/system/tests/modules/form_test/src/Form/FormTestVerticalTabsAccessForm.php
+++ b/core/modules/system/tests/modules/form_test/src/Form/FormTestVerticalTabsAccessForm.php
@@ -130,7 +130,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message(t('The form submitted correctly.'));
+    $this->messenger()->addStatus(t('The form submitted correctly.'));
   }
 
 }
diff --git a/core/modules/system/tests/modules/form_test/src/FormTestArgumentsObject.php b/core/modules/system/tests/modules/form_test/src/FormTestArgumentsObject.php
index 0d86a2d7aed4..8667ca9a653f 100644
--- a/core/modules/system/tests/modules/form_test/src/FormTestArgumentsObject.php
+++ b/core/modules/system/tests/modules/form_test/src/FormTestArgumentsObject.php
@@ -50,14 +50,14 @@ public function buildForm(array $form, FormStateInterface $form_state, $arg = NU
    * {@inheritdoc}
    */
   public function validateForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message($this->t('The FormTestArgumentsObject::validateForm() method was used for this form.'));
+    $this->messenger()->addStatus($this->t('The FormTestArgumentsObject::validateForm() method was used for this form.'));
   }
 
   /**
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message($this->t('The FormTestArgumentsObject::submitForm() method was used for this form.'));
+    $this->messenger()->addStatus($this->t('The FormTestArgumentsObject::submitForm() method was used for this form.'));
     $this->config('form_test.object')
       ->set('bananas', $form_state->getValue('bananas'))
       ->save();
diff --git a/core/modules/system/tests/modules/form_test/src/FormTestControllerObject.php b/core/modules/system/tests/modules/form_test/src/FormTestControllerObject.php
index 40d474d7aa1c..428e9cef35f0 100644
--- a/core/modules/system/tests/modules/form_test/src/FormTestControllerObject.php
+++ b/core/modules/system/tests/modules/form_test/src/FormTestControllerObject.php
@@ -32,7 +32,7 @@ protected function getEditableConfigNames() {
    * {@inheritdoc}
    */
   public static function create(ContainerInterface $container) {
-    drupal_set_message(t('The FormTestControllerObject::create() method was used for this form.'));
+    \Drupal::messenger()->addStatus(t('The FormTestControllerObject::create() method was used for this form.'));
     return new static(
       $container->get('config.factory')
     );
@@ -64,14 +64,14 @@ public function buildForm(array $form, FormStateInterface $form_state, Request $
    * {@inheritdoc}
    */
   public function validateForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message($this->t('The FormTestControllerObject::validateForm() method was used for this form.'));
+    $this->messenger()->addStatus($this->t('The FormTestControllerObject::validateForm() method was used for this form.'));
   }
 
   /**
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message($this->t('The FormTestControllerObject::submitForm() method was used for this form.'));
+    $this->messenger()->addStatus($this->t('The FormTestControllerObject::submitForm() method was used for this form.'));
     $this->config('form_test.object')
       ->set('bananas', $form_state->getValue('bananas'))
       ->save();
diff --git a/core/modules/system/tests/modules/form_test/src/FormTestObject.php b/core/modules/system/tests/modules/form_test/src/FormTestObject.php
index d7fd119c750a..3db579e9438b 100644
--- a/core/modules/system/tests/modules/form_test/src/FormTestObject.php
+++ b/core/modules/system/tests/modules/form_test/src/FormTestObject.php
@@ -57,14 +57,14 @@ public function buildForm(array $form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function validateForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message($this->t('The FormTestObject::validateForm() method was used for this form.'));
+    $this->messenger()->addStatus($this->t('The FormTestObject::validateForm() method was used for this form.'));
   }
 
   /**
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message($this->t('The FormTestObject::submitForm() method was used for this form.'));
+    $this->messenger()->addStatus($this->t('The FormTestObject::submitForm() method was used for this form.'));
     $this->config('form_test.object')
       ->set('bananas', $form_state->getValue('bananas'))
       ->save();
diff --git a/core/modules/system/tests/modules/form_test/src/FormTestServiceObject.php b/core/modules/system/tests/modules/form_test/src/FormTestServiceObject.php
index c1d8555552d9..f4a89bf9fd4e 100644
--- a/core/modules/system/tests/modules/form_test/src/FormTestServiceObject.php
+++ b/core/modules/system/tests/modules/form_test/src/FormTestServiceObject.php
@@ -50,14 +50,14 @@ public function buildForm(array $form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function validateForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message($this->t('The FormTestServiceObject::validateForm() method was used for this form.'));
+    $this->messenger()->addStatus($this->t('The FormTestServiceObject::validateForm() method was used for this form.'));
   }
 
   /**
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message($this->t('The FormTestServiceObject::submitForm() method was used for this form.'));
+    $this->messenger()->addStatus($this->t('The FormTestServiceObject::submitForm() method was used for this form.'));
     $this->config('form_test.object', FALSE)
       ->set('bananas', $form_state->getValue('bananas'))
       ->save();
diff --git a/core/modules/system/tests/modules/pager_test/src/Controller/PagerTestController.php b/core/modules/system/tests/modules/pager_test/src/Controller/PagerTestController.php
index 1964f740fe97..3253b0c9bd0f 100644
--- a/core/modules/system/tests/modules/pager_test/src/Controller/PagerTestController.php
+++ b/core/modules/system/tests/modules/pager_test/src/Controller/PagerTestController.php
@@ -118,7 +118,7 @@ public function multiplePagers() {
    * #pre_render callback for #type => pager that shows the pager cache context.
    */
   public static function showPagerCacheContext(array $pager) {
-    drupal_set_message(\Drupal::service('cache_contexts_manager')->convertTokensToKeys(['url.query_args.pagers:' . $pager['#element']])->getKeys()[0]);
+    \Drupal::messenger()->addStatus(\Drupal::service('cache_contexts_manager')->convertTokensToKeys(['url.query_args.pagers:' . $pager['#element']])->getKeys()[0]);
     return $pager;
   }
 
diff --git a/core/modules/system/tests/modules/render_placeholder_message_test/src/RenderPlaceholderMessageTestController.php b/core/modules/system/tests/modules/render_placeholder_message_test/src/RenderPlaceholderMessageTestController.php
index 4a4d15d8971b..ddb76e6dc054 100644
--- a/core/modules/system/tests/modules/render_placeholder_message_test/src/RenderPlaceholderMessageTestController.php
+++ b/core/modules/system/tests/modules/render_placeholder_message_test/src/RenderPlaceholderMessageTestController.php
@@ -91,7 +91,7 @@ protected function build(array $placeholder_order) {
    */
   public static function setAndLogMessage($message) {
     // Set message.
-    drupal_set_message($message);
+    \Drupal::messenger()->addStatus($message);
 
     // Print which message is expected.
     return ['#markup' => '<p class="logged-message">Message: ' . $message . '</p>'];
diff --git a/core/modules/system/tests/modules/service_provider_test/src/TestClass.php b/core/modules/system/tests/modules/service_provider_test/src/TestClass.php
index d521e1fdb99a..c4dad85955c8 100644
--- a/core/modules/system/tests/modules/service_provider_test/src/TestClass.php
+++ b/core/modules/system/tests/modules/service_provider_test/src/TestClass.php
@@ -36,7 +36,7 @@ public function __construct(StateInterface $state) {
    * A simple kernel listener method.
    */
   public function onKernelRequestTest(GetResponseEvent $event) {
-    drupal_set_message(t('The service_provider_test event subscriber fired!'));
+    \Drupal::messenger()->addStatus(t('The service_provider_test event subscriber fired!'));
   }
 
   /**
diff --git a/core/modules/system/tests/modules/session_test/src/Controller/SessionTestController.php b/core/modules/system/tests/modules/session_test/src/Controller/SessionTestController.php
index 76a54629425e..1094522eabc5 100644
--- a/core/modules/system/tests/modules/session_test/src/Controller/SessionTestController.php
+++ b/core/modules/system/tests/modules/session_test/src/Controller/SessionTestController.php
@@ -110,7 +110,7 @@ public function noSet($test_value) {
    *   A notification message.
    */
   public function setMessage() {
-    drupal_set_message($this->t('This is a dummy message.'));
+    $this->messenger()->addStatus($this->t('This is a dummy message.'));
     return new Response($this->t('A message was set.'));
     // Do not return anything, so the current request does not result in a themed
     // page with messages. The message will be displayed in the following request
diff --git a/core/modules/system/tests/modules/session_test/src/Form/SessionTestForm.php b/core/modules/system/tests/modules/session_test/src/Form/SessionTestForm.php
index c09237ac6bdb..57c13a32cc3c 100644
--- a/core/modules/system/tests/modules/session_test/src/Form/SessionTestForm.php
+++ b/core/modules/system/tests/modules/session_test/src/Form/SessionTestForm.php
@@ -43,7 +43,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    drupal_set_message(SafeMarkup::format('Ok: @input', ['@input' => $form_state->getValue('input')]));
+    $this->messenger()->addStatus(SafeMarkup::format('Ok: @input', ['@input' => $form_state->getValue('input')]));
   }
 
 }
diff --git a/core/modules/system/tests/modules/system_test/src/Controller/SystemTestController.php b/core/modules/system/tests/modules/system_test/src/Controller/SystemTestController.php
index e350bc2eaf37..aaa56d0993e8 100644
--- a/core/modules/system/tests/modules/system_test/src/Controller/SystemTestController.php
+++ b/core/modules/system/tests/modules/system_test/src/Controller/SystemTestController.php
@@ -109,8 +109,8 @@ public function mainContentFallback() {
    */
   public function drupalSetMessageTest() {
     // Set two messages.
-    drupal_set_message('First message (removed).');
-    drupal_set_message(t('Second message with <em>markup!</em> (not removed).'));
+    $this->messenger->addStatus('First message (removed).');
+    $this->messenger->addStatus($this->t('Second message with <em>markup!</em> (not removed).'));
     $messages = $this->messenger->deleteByType('status');
     // Remove the first.
     unset($messages[0]);
@@ -120,27 +120,27 @@ public function drupalSetMessageTest() {
     }
 
     // Duplicate message check.
-    drupal_set_message('Non Duplicated message', 'status', FALSE);
-    drupal_set_message('Non Duplicated message', 'status', FALSE);
+    $this->messenger->addStatus('Non Duplicated message');
+    $this->messenger->addStatus('Non Duplicated message');
 
-    drupal_set_message('Duplicated message', 'status', TRUE);
-    drupal_set_message('Duplicated message', 'status', TRUE);
+    $this->messenger->addStatus('Duplicated message', TRUE);
+    $this->messenger->addStatus('Duplicated message', TRUE);
 
     // Add a Markup message.
-    drupal_set_message(Markup::create('Markup with <em>markup!</em>'));
+    $this->messenger->addStatus(Markup::create('Markup with <em>markup!</em>'));
     // Test duplicate Markup messages.
-    drupal_set_message(Markup::create('Markup with <em>markup!</em>'));
+    $this->messenger->addStatus(Markup::create('Markup with <em>markup!</em>'));
     // Ensure that multiple Markup messages work.
-    drupal_set_message(Markup::create('Markup2 with <em>markup!</em>'));
+    $this->messenger->addStatus(Markup::create('Markup2 with <em>markup!</em>'));
 
     // Test mixing of types.
-    drupal_set_message(Markup::create('Non duplicate Markup / string.'));
-    drupal_set_message('Non duplicate Markup / string.');
-    drupal_set_message(Markup::create('Duplicate Markup / string.'), 'status', TRUE);
-    drupal_set_message('Duplicate Markup / string.', 'status', TRUE);
+    $this->messenger->addStatus(Markup::create('Non duplicate Markup / string.'));
+    $this->messenger->addStatus('Non duplicate Markup / string.');
+    $this->messenger->addStatus(Markup::create('Duplicate Markup / string.'), TRUE);
+    $this->messenger->addStatus('Duplicate Markup / string.', TRUE);
 
     // Test auto-escape of non safe strings.
-    drupal_set_message('<em>This<span>markup will be</span> escaped</em>.');
+    $this->messenger->addStatus('<em>This<span>markup will be</span> escaped</em>.');
 
     return [];
   }
diff --git a/core/modules/system/tests/modules/system_test/system_test.module b/core/modules/system/tests/modules/system_test/system_test.module
index 81739086c327..affc20ea4203 100644
--- a/core/modules/system/tests/modules/system_test/system_test.module
+++ b/core/modules/system/tests/modules/system_test/system_test.module
@@ -27,7 +27,7 @@ function system_test_help($route_name, RouteMatchInterface $route_match) {
 function system_test_modules_installed($modules) {
   if (\Drupal::state()->get('system_test.verbose_module_hooks')) {
     foreach ($modules as $module) {
-      drupal_set_message(t('hook_modules_installed fired for @module', ['@module' => $module]));
+      \Drupal::messenger()->addStatus(t('hook_modules_installed fired for @module', ['@module' => $module]));
     }
   }
 }
@@ -38,7 +38,7 @@ function system_test_modules_installed($modules) {
 function system_test_modules_uninstalled($modules) {
   if (\Drupal::state()->get('system_test.verbose_module_hooks')) {
     foreach ($modules as $module) {
-      drupal_set_message(t('hook_modules_uninstalled fired for @module', ['@module' => $module]));
+      \Drupal::messenger()->addStatus(t('hook_modules_uninstalled fired for @module', ['@module' => $module]));
     }
   }
 }
@@ -90,7 +90,7 @@ function system_test_page_attachments(array &$page) {
   // \Drupal::service('path.matcher')->isFrontPage().
   $frontpage = \Drupal::state()->get('system_test.front_page_output') ?: 0;
   if ($frontpage && \Drupal::service('path.matcher')->isFrontPage()) {
-    drupal_set_message(t('On front page.'));
+    \Drupal::messenger()->addStatus(t('On front page.'));
   }
 }
 
diff --git a/core/modules/system/tests/modules/theme_suggestions_test/theme_suggestions_test.module b/core/modules/system/tests/modules/theme_suggestions_test/theme_suggestions_test.module
index 50fb86d2b83f..cbc5b380206a 100644
--- a/core/modules/system/tests/modules/theme_suggestions_test/theme_suggestions_test.module
+++ b/core/modules/system/tests/modules/theme_suggestions_test/theme_suggestions_test.module
@@ -21,7 +21,7 @@ function theme_suggestions_test_theme() {
  * Implements hook_theme_suggestions_alter().
  */
 function theme_suggestions_test_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
-  drupal_set_message(__FUNCTION__ . '() executed.');
+  \Drupal::messenger()->addStatus(__FUNCTION__ . '() executed.');
   if ($hook == 'theme_test_general_suggestions') {
     $suggestions[] = $hook . '__module_override';
   }
@@ -31,7 +31,7 @@ function theme_suggestions_test_theme_suggestions_alter(array &$suggestions, arr
  * Implements hook_theme_suggestions_HOOK_alter().
  */
 function theme_suggestions_test_theme_suggestions_theme_test_suggestions_alter(array &$suggestions, array $variables) {
-  drupal_set_message(__FUNCTION__ . '() executed.');
+  \Drupal::messenger()->addStatus(__FUNCTION__ . '() executed.');
   $suggestions[] = 'theme_test_suggestions__' . 'module_override';
 }
 
diff --git a/core/modules/system/tests/modules/theme_test/theme_test.module b/core/modules/system/tests/modules/theme_test/theme_test.module
index cd8aba7da7bc..f971b5453a48 100644
--- a/core/modules/system/tests/modules/theme_test/theme_test.module
+++ b/core/modules/system/tests/modules/theme_test/theme_test.module
@@ -178,14 +178,14 @@ function theme_test_theme_suggestions_theme_test_suggestion_provided(array $vari
  * Implements hook_theme_suggestions_alter().
  */
 function theme_test_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
-  drupal_set_message(__FUNCTION__ . '() executed.');
+  \Drupal::messenger()->addStatus(__FUNCTION__ . '() executed.');
 }
 
 /**
  * Implements hook_theme_suggestions_HOOK_alter().
  */
 function theme_test_theme_suggestions_theme_test_suggestions_alter(array &$suggestions, array $variables) {
-  drupal_set_message(__FUNCTION__ . '() executed.');
+  \Drupal::messenger()->addStatus(__FUNCTION__ . '() executed.');
 }
 
 /**
diff --git a/core/modules/system/tests/modules/update_script_test/update_script_test.module b/core/modules/system/tests/modules/update_script_test/update_script_test.module
index 986dc31ab3f1..096f91251596 100644
--- a/core/modules/system/tests/modules/update_script_test/update_script_test.module
+++ b/core/modules/system/tests/modules/update_script_test/update_script_test.module
@@ -14,5 +14,5 @@
  * @see UpdateScriptFunctionalTest::testRequirements()
  */
 function update_script_test_cache_flush() {
-  drupal_set_message(t('hook_cache_flush() invoked for update_script_test.module.'));
+  \Drupal::messenger()->addStatus(t('hook_cache_flush() invoked for update_script_test.module.'));
 }
diff --git a/core/modules/system/tests/src/Functional/Form/FormTest.php b/core/modules/system/tests/src/Functional/Form/FormTest.php
index 87c763245786..d28cfa3f02d7 100644
--- a/core/modules/system/tests/src/Functional/Form/FormTest.php
+++ b/core/modules/system/tests/src/Functional/Form/FormTest.php
@@ -151,7 +151,7 @@ public function testRequiredFields() {
       }
     }
     // Clear the expected form error messages so they don't appear as exceptions.
-    drupal_get_messages();
+    \Drupal::messenger()->deleteAll();
   }
 
   /**
diff --git a/core/modules/system/tests/src/Functional/Module/InstallUninstallTest.php b/core/modules/system/tests/src/Functional/Module/InstallUninstallTest.php
index 4d8f30d65c7f..c3fcb758fb8e 100644
--- a/core/modules/system/tests/src/Functional/Module/InstallUninstallTest.php
+++ b/core/modules/system/tests/src/Functional/Module/InstallUninstallTest.php
@@ -22,7 +22,8 @@ class InstallUninstallTest extends ModuleTestBase {
    */
   public function testInstallUninstall() {
     // Set a variable so that the hook implementations in system_test.module
-    // will display messages via drupal_set_message().
+    // will display messages via
+    // \Drupal\Core\Messenger\MessengerInterface::addStatus().
     $this->container->get('state')->set('system_test.verbose_module_hooks', TRUE);
 
     // Install and uninstall module_test to ensure hook_preinstall_module and
diff --git a/core/modules/system/tests/src/Functional/ServiceProvider/ServiceProviderWebTest.php b/core/modules/system/tests/src/Functional/ServiceProvider/ServiceProviderWebTest.php
index 73d6910087df..5e86164f6e6d 100644
--- a/core/modules/system/tests/src/Functional/ServiceProvider/ServiceProviderWebTest.php
+++ b/core/modules/system/tests/src/Functional/ServiceProvider/ServiceProviderWebTest.php
@@ -26,9 +26,10 @@ class ServiceProviderWebTest extends BrowserTestBase {
    */
   public function testServiceProviderRegistrationIntegration() {
     $this->assertTrue(\Drupal::hasService('service_provider_test_class'), 'The service_provider_test_class service has been registered to the DIC');
-    // The event subscriber method in the test class calls drupal_set_message()
-    // with a message saying it has fired. This will fire on every page request
-    // so it should show up on the front page.
+    // The event subscriber method in the test class calls
+    // \Drupal\Core\Messenger\MessengerInterface::addStatus() with a message
+    // saying it has fired. This will fire on every page request so it should
+    // show up on the front page.
     $this->drupalGet('');
     $this->assertText(t('The service_provider_test event subscriber fired!'), 'The service_provider_test event subscriber fired');
   }
diff --git a/core/modules/system/tests/src/Kernel/Render/ClassyTest.php b/core/modules/system/tests/src/Kernel/Render/ClassyTest.php
index 8dbb01e5d057..8d1cb8548126 100644
--- a/core/modules/system/tests/src/Kernel/Render/ClassyTest.php
+++ b/core/modules/system/tests/src/Kernel/Render/ClassyTest.php
@@ -37,8 +37,8 @@ public function setUp() {
    * Test the classy theme.
    */
   public function testClassyTheme() {
-    drupal_set_message('An error occurred', 'error');
-    drupal_set_message('But then something nice happened');
+    \Drupal::messenger()->addError('An error occurred');
+    \Drupal::messenger()->addStatus('But then something nice happened');
     $messages = [
       '#type' => 'status_messages',
     ];
diff --git a/core/modules/system/tests/themes/test_theme/test_theme.theme b/core/modules/system/tests/themes/test_theme/test_theme.theme
index aa399b66c537..423390d2225c 100644
--- a/core/modules/system/tests/themes/test_theme/test_theme.theme
+++ b/core/modules/system/tests/themes/test_theme/test_theme.theme
@@ -53,7 +53,7 @@ function test_theme_theme_test_alter_alter(&$data) {
  * Implements hook_theme_suggestions_alter().
  */
 function test_theme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
-  drupal_set_message(__FUNCTION__ . '() executed.');
+  \Drupal::messenger()->addStatus(__FUNCTION__ . '() executed.');
   // Theme alter hooks run after module alter hooks, so add this theme
   // suggestion to the beginning of the array so that the suggestion added by
   // the theme_suggestions_test module can be picked up when that module is
@@ -67,7 +67,7 @@ function test_theme_theme_suggestions_alter(array &$suggestions, array $variable
  * Implements hook_theme_suggestions_HOOK_alter().
  */
 function test_theme_theme_suggestions_theme_test_suggestions_alter(array &$suggestions, array $variables) {
-  drupal_set_message(__FUNCTION__ . '() executed.');
+  \Drupal::messenger()->addStatus(__FUNCTION__ . '() executed.');
   // Theme alter hooks run after module alter hooks, so add this theme
   // suggestion to the beginning of the array so that the suggestion added by
   // the theme_suggestions_test module can be picked up when that module is
diff --git a/core/modules/taxonomy/src/Form/OverviewTerms.php b/core/modules/taxonomy/src/Form/OverviewTerms.php
index 8c0f390d3bee..f9e0d595982e 100644
--- a/core/modules/taxonomy/src/Form/OverviewTerms.php
+++ b/core/modules/taxonomy/src/Form/OverviewTerms.php
@@ -497,7 +497,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $vocabulary->setHierarchy($hierarchy);
       $vocabulary->save();
     }
-    drupal_set_message($this->t('The configuration options have been saved.'));
+    $this->messenger()->addStatus($this->t('The configuration options have been saved.'));
   }
 
   /**
diff --git a/core/modules/taxonomy/src/Form/VocabularyResetForm.php b/core/modules/taxonomy/src/Form/VocabularyResetForm.php
index 439d994cf104..c7ea78f7c02c 100644
--- a/core/modules/taxonomy/src/Form/VocabularyResetForm.php
+++ b/core/modules/taxonomy/src/Form/VocabularyResetForm.php
@@ -82,7 +82,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     parent::submitForm($form, $form_state);
     $this->termStorage->resetWeights($this->entity->id());
 
-    drupal_set_message($this->t('Reset vocabulary %name to alphabetical order.', ['%name' => $this->entity->label()]));
+    $this->messenger()->addStatus($this->t('Reset vocabulary %name to alphabetical order.', ['%name' => $this->entity->label()]));
     $this->logger('taxonomy')->notice('Reset vocabulary %name to alphabetical order.', ['%name' => $this->entity->label()]);
     $form_state->setRedirectUrl($this->getCancelUrl());
   }
diff --git a/core/modules/taxonomy/src/TermForm.php b/core/modules/taxonomy/src/TermForm.php
index 6de48e0af4b6..95909bd3b174 100644
--- a/core/modules/taxonomy/src/TermForm.php
+++ b/core/modules/taxonomy/src/TermForm.php
@@ -132,11 +132,11 @@ public function save(array $form, FormStateInterface $form_state) {
     $view_link = $term->link($term->getName());
     switch ($result) {
       case SAVED_NEW:
-        drupal_set_message($this->t('Created new term %term.', ['%term' => $view_link]));
+        $this->messenger()->addStatus($this->t('Created new term %term.', ['%term' => $view_link]));
         $this->logger('taxonomy')->notice('Created new term %term.', ['%term' => $term->getName(), 'link' => $edit_link]);
         break;
       case SAVED_UPDATED:
-        drupal_set_message($this->t('Updated term %term.', ['%term' => $view_link]));
+        $this->messenger()->addStatus($this->t('Updated term %term.', ['%term' => $view_link]));
         $this->logger('taxonomy')->notice('Updated term %term.', ['%term' => $term->getName(), 'link' => $edit_link]);
         break;
     }
diff --git a/core/modules/taxonomy/src/VocabularyForm.php b/core/modules/taxonomy/src/VocabularyForm.php
index 42162caa563e..83603e370222 100644
--- a/core/modules/taxonomy/src/VocabularyForm.php
+++ b/core/modules/taxonomy/src/VocabularyForm.php
@@ -125,13 +125,13 @@ public function save(array $form, FormStateInterface $form_state) {
     $edit_link = $this->entity->link($this->t('Edit'));
     switch ($status) {
       case SAVED_NEW:
-        drupal_set_message($this->t('Created new vocabulary %name.', ['%name' => $vocabulary->label()]));
+        $this->messenger()->addStatus($this->t('Created new vocabulary %name.', ['%name' => $vocabulary->label()]));
         $this->logger('taxonomy')->notice('Created new vocabulary %name.', ['%name' => $vocabulary->label(), 'link' => $edit_link]);
         $form_state->setRedirectUrl($vocabulary->urlInfo('overview-form'));
         break;
 
       case SAVED_UPDATED:
-        drupal_set_message($this->t('Updated vocabulary %name.', ['%name' => $vocabulary->label()]));
+        $this->messenger()->addStatus($this->t('Updated vocabulary %name.', ['%name' => $vocabulary->label()]));
         $this->logger('taxonomy')->notice('Updated vocabulary %name.', ['%name' => $vocabulary->label(), 'link' => $edit_link]);
         $form_state->setRedirectUrl($vocabulary->urlInfo('collection'));
         break;
diff --git a/core/modules/taxonomy/src/VocabularyListBuilder.php b/core/modules/taxonomy/src/VocabularyListBuilder.php
index 645ebd161d3d..7ae420f12d7e 100644
--- a/core/modules/taxonomy/src/VocabularyListBuilder.php
+++ b/core/modules/taxonomy/src/VocabularyListBuilder.php
@@ -7,6 +7,7 @@
 use Drupal\Core\Entity\EntityTypeInterface;
 use Drupal\Core\Entity\EntityTypeManagerInterface;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Core\Render\RendererInterface;
 use Drupal\Core\Session\AccountInterface;
 use Drupal\Core\Url;
@@ -45,6 +46,13 @@ class VocabularyListBuilder extends DraggableListBuilder {
    */
   protected $renderer;
 
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
   /**
    * Constructs a new VocabularyListBuilder object.
    *
@@ -56,13 +64,20 @@ class VocabularyListBuilder extends DraggableListBuilder {
    *   The entity manager service.
    * @param \Drupal\Core\Render\RendererInterface $renderer
    *   The renderer service.
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   The messenger.
    */
-  public function __construct(EntityTypeInterface $entity_type, AccountInterface $current_user, EntityTypeManagerInterface $entity_type_manager, RendererInterface $renderer = NULL) {
+  public function __construct(EntityTypeInterface $entity_type,
+                              AccountInterface $current_user,
+                              EntityTypeManagerInterface $entity_type_manager,
+                              RendererInterface $renderer = NULL,
+                              MessengerInterface $messenger) {
     parent::__construct($entity_type, $entity_type_manager->getStorage($entity_type->id()));
 
     $this->currentUser = $current_user;
     $this->entityTypeManager = $entity_type_manager;
     $this->renderer = $renderer;
+    $this->messenger = $messenger;
   }
 
   /**
@@ -73,7 +88,8 @@ public static function createInstance(ContainerInterface $container, EntityTypeI
       $entity_type,
       $container->get('current_user'),
       $container->get('entity_type.manager'),
-      $container->get('renderer')
+      $container->get('renderer'),
+      $container->get('messenger')
     );
   }
 
@@ -189,7 +205,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
   public function submitForm(array &$form, FormStateInterface $form_state) {
     parent::submitForm($form, $form_state);
 
-    drupal_set_message(t('The configuration options have been saved.'));
+    $this->messenger->addStatus($this->t('The configuration options have been saved.'));
   }
 
 }
diff --git a/core/modules/update/src/Form/UpdateManagerInstall.php b/core/modules/update/src/Form/UpdateManagerInstall.php
index 55f0440908f0..c3fed3848270 100644
--- a/core/modules/update/src/Form/UpdateManagerInstall.php
+++ b/core/modules/update/src/Form/UpdateManagerInstall.php
@@ -139,7 +139,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     if ($form_state->getValue('project_url')) {
       $local_cache = update_manager_file_get($form_state->getValue('project_url'));
       if (!$local_cache) {
-        drupal_set_message($this->t('Unable to retrieve Drupal project from %url.', ['%url' => $form_state->getValue('project_url')]), 'error');
+        $this->messenger()->addError($this->t('Unable to retrieve Drupal project from %url.', ['%url' => $form_state->getValue('project_url')]));
         return;
       }
     }
@@ -147,7 +147,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $validators = ['file_validate_extensions' => [archiver_get_extensions()]];
       if (!($finfo = file_save_upload('project_upload', $validators, NULL, 0, FILE_EXISTS_REPLACE))) {
         // Failed to upload the file. file_save_upload() calls
-        // drupal_set_message() on failure.
+        // \Drupal\Core\Messenger\MessengerInterface::addError() on failure.
         return;
       }
       $local_cache = $finfo->getFileUri();
@@ -158,13 +158,13 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $archive = update_manager_archive_extract($local_cache, $directory);
     }
     catch (\Exception $e) {
-      drupal_set_message($e->getMessage(), 'error');
+      $this->messenger()->addError($e->getMessage());
       return;
     }
 
     $files = $archive->listContents();
     if (!$files) {
-      drupal_set_message($this->t('Provided archive contains no files.'), 'error');
+      $this->messenger()->addError($this->t('Provided archive contains no files.'));
       return;
     }
 
@@ -175,12 +175,12 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
 
     $archive_errors = $this->moduleHandler->invokeAll('verify_update_archive', [$project, $local_cache, $directory]);
     if (!empty($archive_errors)) {
-      drupal_set_message(array_shift($archive_errors), 'error');
+      $this->messenger()->addError(array_shift($archive_errors));
       // @todo: Fix me in D8: We need a way to set multiple errors on the same
       // form element and have all of them appear!
       if (!empty($archive_errors)) {
         foreach ($archive_errors as $error) {
-          drupal_set_message($error, 'error');
+          $this->messenger()->addError($error);
         }
       }
       return;
@@ -194,7 +194,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $updater = Updater::factory($project_location, $this->root);
     }
     catch (\Exception $e) {
-      drupal_set_message($e->getMessage(), 'error');
+      $this->messenger()->addError($e->getMessage());
       return;
     }
 
@@ -202,16 +202,16 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $project_title = Updater::getProjectTitle($project_location);
     }
     catch (\Exception $e) {
-      drupal_set_message($e->getMessage(), 'error');
+      $this->messenger()->addError($e->getMessage());
       return;
     }
 
     if (!$project_title) {
-      drupal_set_message($this->t('Unable to determine %project name.', ['%project' => $project]), 'error');
+      $this->messenger()->addError($this->t('Unable to determine %project name.', ['%project' => $project]));
     }
 
     if ($updater->isInstalled()) {
-      drupal_set_message($this->t('%project is already installed.', ['%project' => $project_title]), 'error');
+      $this->messenger()->addError($this->t('%project is already installed.', ['%project' => $project_title]));
       return;
     }
 
diff --git a/core/modules/update/tests/src/Functional/UpdateCoreTest.php b/core/modules/update/tests/src/Functional/UpdateCoreTest.php
index 5cd4b1026068..222d56858027 100644
--- a/core/modules/update/tests/src/Functional/UpdateCoreTest.php
+++ b/core/modules/update/tests/src/Functional/UpdateCoreTest.php
@@ -289,8 +289,9 @@ public function testModulePageSecurityUpdate() {
     // Make sure duplicate messages don't appear on Update status pages.
     $this->drupalGet('admin/reports/status');
     // We're expecting "There is a security update..." inside the status report
-    // itself, but the drupal_set_message() appears as an li so we can prefix
-    // with that and search for the raw HTML.
+    // itself, but the message from
+    // \Drupal\Core\Messenger\MessengerInterface::addStatus() appears as an li
+    // so we can prefix with that and search for the raw HTML.
     $this->assertNoRaw('<li>' . t('There is a security update available for your version of Drupal.'));
 
     $this->drupalGet('admin/reports/updates');
diff --git a/core/modules/update/update.manager.inc b/core/modules/update/update.manager.inc
index 2229f0a205a8..c3f4681e75ae 100644
--- a/core/modules/update/update.manager.inc
+++ b/core/modules/update/update.manager.inc
@@ -53,17 +53,17 @@ function update_manager_download_batch_finished($success, $results) {
       '#title' => t('Downloading updates failed:'),
       '#items' => $results['errors'],
     ];
-    drupal_set_message(\Drupal::service('renderer')->render($item_list), 'error');
+    \Drupal::messenger()->addError(\Drupal::service('renderer')->render($item_list));
   }
   elseif ($success) {
-    drupal_set_message(t('Updates downloaded successfully.'));
+    \Drupal::messenger()->addStatus(t('Updates downloaded successfully.'));
     $_SESSION['update_manager_update_projects'] = $results['projects'];
     return new RedirectResponse(\Drupal::url('update.confirmation_page', [], ['absolute' => TRUE]));
   }
   else {
     // Ideally we're catching all Exceptions, so they should never see this,
     // but just in case, we have to tell them something.
-    drupal_set_message(t('Fatal error trying to download.'), 'error');
+    \Drupal::messenger()->addError(t('Fatal error trying to download.'));
   }
 }
 
diff --git a/core/modules/update/update.module b/core/modules/update/update.module
index a7e8cc339712..992dec6dd98a 100644
--- a/core/modules/update/update.module
+++ b/core/modules/update/update.module
@@ -185,17 +185,18 @@ function update_page_top() {
     foreach (['core', 'contrib'] as $report_type) {
       $type = 'update_' . $report_type;
       // hook_requirements() supports render arrays therefore we need to render
-      // them before using drupal_set_message().
+      // them before using
+      // \Drupal\Core\Messenger\MessengerInterface::addStatus().
       if (isset($status[$type]['description']) && is_array($status[$type]['description'])) {
         $status[$type]['description'] = \Drupal::service('renderer')->renderPlain($status[$type]['description']);
       }
       if (!empty($verbose)) {
         if (isset($status[$type]['severity'])) {
           if ($status[$type]['severity'] == REQUIREMENT_ERROR) {
-            drupal_set_message($status[$type]['description'], 'error');
+            \Drupal::messenger()->addError($status[$type]['description']);
           }
           elseif ($status[$type]['severity'] == REQUIREMENT_WARNING) {
-            drupal_set_message($status[$type]['description'], 'warning');
+            \Drupal::messenger()->addWarning($status[$type]['description']);
           }
         }
       }
@@ -205,7 +206,7 @@ function update_page_top() {
         if (isset($status[$type])
             && isset($status[$type]['reason'])
             && $status[$type]['reason'] === UPDATE_NOT_SECURE) {
-          drupal_set_message($status[$type]['description'], 'error');
+          \Drupal::messenger()->addError($status[$type]['description']);
         }
       }
     }
@@ -455,15 +456,15 @@ function update_fetch_data_finished($success, $results) {
   if ($success) {
     if (!empty($results)) {
       if (!empty($results['updated'])) {
-        drupal_set_message(\Drupal::translation()->formatPlural($results['updated'], 'Checked available update data for one project.', 'Checked available update data for @count projects.'));
+        \Drupal::messenger()->addStatus(\Drupal::translation()->formatPlural($results['updated'], 'Checked available update data for one project.', 'Checked available update data for @count projects.'));
       }
       if (!empty($results['failures'])) {
-        drupal_set_message(\Drupal::translation()->formatPlural($results['failures'], 'Failed to get available update data for one project.', 'Failed to get available update data for @count projects.'), 'error');
+        \Drupal::messenger()->addError(\Drupal::translation()->formatPlural($results['failures'], 'Failed to get available update data for one project.', 'Failed to get available update data for @count projects.'));
       }
     }
   }
   else {
-    drupal_set_message(t('An error occurred trying to get available update data.'), 'error');
+    \Drupal::messenger()->addError(t('An error occurred trying to get available update data.'), 'error');
   }
 }
 
diff --git a/core/modules/user/src/Controller/UserController.php b/core/modules/user/src/Controller/UserController.php
index be15fac4ab8d..eba37a9f644d 100644
--- a/core/modules/user/src/Controller/UserController.php
+++ b/core/modules/user/src/Controller/UserController.php
@@ -120,12 +120,17 @@ public function resetPass(Request $request, $uid, $timestamp, $hash) {
       else {
         /** @var \Drupal\user\UserInterface $reset_link_user */
         if ($reset_link_user = $this->userStorage->load($uid)) {
-          drupal_set_message($this->t('Another user (%other_user) is already logged into the site on this computer, but you tried to use a one-time link for user %resetting_user. Please <a href=":logout">log out</a> and try using the link again.',
-            ['%other_user' => $account->getUsername(), '%resetting_user' => $reset_link_user->getUsername(), ':logout' => $this->url('user.logout')]), 'warning');
+          $this->messenger()
+            ->addWarning($this->t('Another user (%other_user) is already logged into the site on this computer, but you tried to use a one-time link for user %resetting_user. Please <a href=":logout">log out</a> and try using the link again.',
+              [
+                '%other_user' => $account->getUsername(),
+                '%resetting_user' => $reset_link_user->getUsername(),
+                ':logout' => $this->url('user.logout'),
+              ]));
         }
         else {
           // Invalid one-time link specifies an unknown user.
-          drupal_set_message($this->t('The one-time login link you clicked is invalid.'), 'error');
+          $this->messenger()->addError($this->t('The one-time login link you clicked is invalid.'));
         }
         return $this->redirect('<front>');
       }
@@ -218,13 +223,13 @@ public function resetPassLogin($uid, $timestamp, $hash) {
     $timeout = $this->config('user.settings')->get('password_reset_timeout');
     // No time out for first time login.
     if ($user->getLastLoginTime() && $current - $timestamp > $timeout) {
-      drupal_set_message($this->t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'), 'error');
+      $this->messenger()->addError($this->t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'));
       return $this->redirect('user.pass');
     }
     elseif ($user->isAuthenticated() && ($timestamp >= $user->getLastLoginTime()) && ($timestamp <= $current) && Crypt::hashEquals($hash, user_pass_rehash($user, $timestamp))) {
       user_login_finalize($user);
       $this->logger->notice('User %name used one-time login link at time %timestamp.', ['%name' => $user->getDisplayName(), '%timestamp' => $timestamp]);
-      drupal_set_message($this->t('You have just used your one-time login link. It is no longer necessary to use this link to log in. Please change your password.'));
+      $this->messenger()->addStatus($this->t('You have just used your one-time login link. It is no longer necessary to use this link to log in. Please change your password.'));
       // Let the user's password be changed without the current password
       // check.
       $token = Crypt::randomBytesBase64(55);
@@ -239,7 +244,7 @@ public function resetPassLogin($uid, $timestamp, $hash) {
       );
     }
 
-    drupal_set_message($this->t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'error');
+    $this->messenger()->addError($this->t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'));
     return $this->redirect('user.pass');
   }
 
@@ -315,7 +320,7 @@ public function confirmCancel(UserInterface $user, $timestamp = 0, $hashed_pass
         return batch_process('');
       }
       else {
-        drupal_set_message(t('You have tried to use an account cancellation link that has expired. Please request a new one using the form below.'), 'error');
+        $this->messenger()->addError($this->t('You have tried to use an account cancellation link that has expired. Please request a new one using the form below.'));
         return $this->redirect('entity.user.cancel_form', ['user' => $user->id()], ['absolute' => TRUE]);
       }
     }
diff --git a/core/modules/user/src/Form/UserCancelForm.php b/core/modules/user/src/Form/UserCancelForm.php
index da7a5f4f9df0..a1fd5f7c86ce 100644
--- a/core/modules/user/src/Form/UserCancelForm.php
+++ b/core/modules/user/src/Form/UserCancelForm.php
@@ -139,7 +139,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       $this->entity->user_cancel_notify = $form_state->getValue('user_cancel_notify');
       $this->entity->save();
       _user_mail_notify('cancel_confirm', $this->entity);
-      drupal_set_message($this->t('A confirmation request to cancel your account has been sent to your email address.'));
+      $this->messenger()->addStatus($this->t('A confirmation request to cancel your account has been sent to your email address.'));
       $this->logger('user')->notice('Sent account cancellation request to %name %email.', ['%name' => $this->entity->label(), '%email' => '<' . $this->entity->getEmail() . '>']);
 
       $form_state->setRedirect(
diff --git a/core/modules/user/src/Form/UserMultipleCancelConfirm.php b/core/modules/user/src/Form/UserMultipleCancelConfirm.php
index b4487c2656a0..b858d6ae2487 100644
--- a/core/modules/user/src/Form/UserMultipleCancelConfirm.php
+++ b/core/modules/user/src/Form/UserMultipleCancelConfirm.php
@@ -5,6 +5,7 @@
 use Drupal\Core\Entity\EntityManagerInterface;
 use Drupal\Core\Form\ConfirmFormBase;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Core\Url;
 use Drupal\Core\TempStore\PrivateTempStoreFactory;
 use Drupal\user\UserStorageInterface;
@@ -132,7 +133,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
     if (isset($root)) {
       $redirect = (count($accounts) == 1);
       $message = $this->t('The user account %name cannot be canceled.', ['%name' => $root->label()]);
-      drupal_set_message($message, $redirect ? 'error' : 'warning');
+      $this->messenger()->addMessage($message, $redirect ? MessengerInterface::TYPE_ERROR : MessengerInterface::TYPE_WARNING);
       // If only user 1 was selected, redirect to the overview.
       if ($redirect) {
         return $this->redirect('entity.user.collection');
diff --git a/core/modules/user/src/Form/UserPasswordForm.php b/core/modules/user/src/Form/UserPasswordForm.php
index a7ae862bb57d..b80564198976 100644
--- a/core/modules/user/src/Form/UserPasswordForm.php
+++ b/core/modules/user/src/Form/UserPasswordForm.php
@@ -140,7 +140,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     $mail = _user_mail_notify('password_reset', $account, $langcode);
     if (!empty($mail)) {
       $this->logger('user')->notice('Password reset instructions mailed to %name at %email.', ['%name' => $account->getUsername(), '%email' => $account->getEmail()]);
-      drupal_set_message($this->t('Further instructions have been sent to your email address.'));
+      $this->messenger()->addStatus($this->t('Further instructions have been sent to your email address.'));
     }
 
     $form_state->setRedirect('user.page');
diff --git a/core/modules/user/src/Form/UserPermissionsForm.php b/core/modules/user/src/Form/UserPermissionsForm.php
index 7d3adaa5dc26..0f7f0378daa0 100644
--- a/core/modules/user/src/Form/UserPermissionsForm.php
+++ b/core/modules/user/src/Form/UserPermissionsForm.php
@@ -216,7 +216,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       user_role_change_permissions($role_name, (array) $form_state->getValue($role_name));
     }
 
-    drupal_set_message($this->t('The changes have been saved.'));
+    $this->messenger()->addStatus($this->t('The changes have been saved.'));
   }
 
 }
diff --git a/core/modules/user/src/ProfileForm.php b/core/modules/user/src/ProfileForm.php
index c856b75da9d4..137868c4f513 100644
--- a/core/modules/user/src/ProfileForm.php
+++ b/core/modules/user/src/ProfileForm.php
@@ -38,7 +38,7 @@ public function save(array $form, FormStateInterface $form_state) {
     $account->save();
     $form_state->setValue('uid', $account->id());
 
-    drupal_set_message($this->t('The changes have been saved.'));
+    $this->messenger()->addStatus($this->t('The changes have been saved.'));
   }
 
   /**
diff --git a/core/modules/user/src/RegisterForm.php b/core/modules/user/src/RegisterForm.php
index 4974e69d8d60..18760f4d4ccd 100644
--- a/core/modules/user/src/RegisterForm.php
+++ b/core/modules/user/src/RegisterForm.php
@@ -103,28 +103,28 @@ public function save(array $form, FormStateInterface $form_state) {
 
     // New administrative account without notification.
     if ($admin && !$notify) {
-      drupal_set_message($this->t('Created a new user account for <a href=":url">%name</a>. No email has been sent.', [':url' => $account->url(), '%name' => $account->getUsername()]));
+      $this->messenger()->addStatus($this->t('Created a new user account for <a href=":url">%name</a>. No email has been sent.', [':url' => $account->url(), '%name' => $account->getUsername()]));
     }
     // No email verification required; log in user immediately.
     elseif (!$admin && !\Drupal::config('user.settings')->get('verify_mail') && $account->isActive()) {
       _user_mail_notify('register_no_approval_required', $account);
       user_login_finalize($account);
-      drupal_set_message($this->t('Registration successful. You are now logged in.'));
+      $this->messenger()->addStatus($this->t('Registration successful. You are now logged in.'));
       $form_state->setRedirect('<front>');
     }
     // No administrator approval required.
     elseif ($account->isActive() || $notify) {
       if (!$account->getEmail() && $notify) {
-        drupal_set_message($this->t('The new user <a href=":url">%name</a> was created without an email address, so no welcome message was sent.', [':url' => $account->url(), '%name' => $account->getUsername()]));
+        $this->messenger()->addStatus($this->t('The new user <a href=":url">%name</a> was created without an email address, so no welcome message was sent.', [':url' => $account->url(), '%name' => $account->getUsername()]));
       }
       else {
         $op = $notify ? 'register_admin_created' : 'register_no_approval_required';
         if (_user_mail_notify($op, $account)) {
           if ($notify) {
-            drupal_set_message($this->t('A welcome message with further instructions has been emailed to the new user <a href=":url">%name</a>.', [':url' => $account->url(), '%name' => $account->getUsername()]));
+            $this->messenger()->addStatus($this->t('A welcome message with further instructions has been emailed to the new user <a href=":url">%name</a>.', [':url' => $account->url(), '%name' => $account->getUsername()]));
           }
           else {
-            drupal_set_message($this->t('A welcome message with further instructions has been sent to your email address.'));
+            $this->messenger()->addStatus($this->t('A welcome message with further instructions has been sent to your email address.'));
             $form_state->setRedirect('<front>');
           }
         }
@@ -133,7 +133,7 @@ public function save(array $form, FormStateInterface $form_state) {
     // Administrator approval required.
     else {
       _user_mail_notify('register_pending_approval', $account);
-      drupal_set_message($this->t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />In the meantime, a welcome message with further instructions has been sent to your email address.'));
+      $this->messenger()->addStatus($this->t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />In the meantime, a welcome message with further instructions has been sent to your email address.'));
       $form_state->setRedirect('<front>');
     }
   }
diff --git a/core/modules/user/src/RoleForm.php b/core/modules/user/src/RoleForm.php
index e40067cf83cd..023159b8709b 100644
--- a/core/modules/user/src/RoleForm.php
+++ b/core/modules/user/src/RoleForm.php
@@ -57,11 +57,11 @@ public function save(array $form, FormStateInterface $form_state) {
 
     $edit_link = $this->entity->link($this->t('Edit'));
     if ($status == SAVED_UPDATED) {
-      drupal_set_message($this->t('Role %label has been updated.', ['%label' => $entity->label()]));
+      $this->messenger()->addStatus($this->t('Role %label has been updated.', ['%label' => $entity->label()]));
       $this->logger('user')->notice('Role %label has been updated.', ['%label' => $entity->label(), 'link' => $edit_link]);
     }
     else {
-      drupal_set_message($this->t('Role %label has been added.', ['%label' => $entity->label()]));
+      $this->messenger()->addStatus($this->t('Role %label has been added.', ['%label' => $entity->label()]));
       $this->logger('user')->notice('Role %label has been added.', ['%label' => $entity->label(), 'link' => $edit_link]);
     }
     $form_state->setRedirect('entity.user_role.collection');
diff --git a/core/modules/user/src/RoleListBuilder.php b/core/modules/user/src/RoleListBuilder.php
index aa3b844fd365..306677a1ef89 100644
--- a/core/modules/user/src/RoleListBuilder.php
+++ b/core/modules/user/src/RoleListBuilder.php
@@ -4,7 +4,11 @@
 
 use Drupal\Core\Config\Entity\DraggableListBuilder;
 use Drupal\Core\Entity\EntityInterface;
+use Drupal\Core\Entity\EntityStorageInterface;
+use Drupal\Core\Entity\EntityTypeInterface;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Messenger\MessengerInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
 
 /**
  * Defines a class to build a listing of user role entities.
@@ -13,6 +17,41 @@
  */
 class RoleListBuilder extends DraggableListBuilder {
 
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
+  /**
+   * RoleListBuilder constructor.
+   *
+   * @param \Drupal\Core\Entity\EntityTypeInterface $entityType
+   *   The entity type definition.
+   * @param \Drupal\Core\Entity\EntityStorageInterface $storage
+   *   The entity storage class.
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   The messenger.
+   */
+  public function __construct(EntityTypeInterface $entityType,
+                              EntityStorageInterface $storage,
+                              MessengerInterface $messenger) {
+    parent::__construct($entityType, $storage);
+    $this->messenger = $messenger;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
+    return new static(
+      $entity_type,
+      $container->get('entity.manager')->getStorage($entity_type->id()),
+      $container->get('messenger')
+    );
+  }
+
   /**
    * {@inheritdoc}
    */
@@ -58,7 +97,7 @@ public function getDefaultOperations(EntityInterface $entity) {
   public function submitForm(array &$form, FormStateInterface $form_state) {
     parent::submitForm($form, $form_state);
 
-    drupal_set_message(t('The role settings have been updated.'));
+    $this->messenger->addStatus($this->t('The role settings have been updated.'));
   }
 
 }
diff --git a/core/modules/user/tests/src/Unit/Plugin/views/field/UserBulkFormTest.php b/core/modules/user/tests/src/Unit/Plugin/views/field/UserBulkFormTest.php
index 11a970a0bf39..a6b2f543f014 100644
--- a/core/modules/user/tests/src/Unit/Plugin/views/field/UserBulkFormTest.php
+++ b/core/modules/user/tests/src/Unit/Plugin/views/field/UserBulkFormTest.php
@@ -54,6 +54,8 @@ public function testConstructor() {
 
     $language_manager = $this->getMock('Drupal\Core\Language\LanguageManagerInterface');
 
+    $messenger = $this->getMock('Drupal\Core\Messenger\MessengerInterface');
+
     $views_data = $this->getMockBuilder('Drupal\views\ViewsData')
       ->disableOriginalConstructor()
       ->getMock();
@@ -84,7 +86,7 @@ public function testConstructor() {
     $definition['title'] = '';
     $options = [];
 
-    $user_bulk_form = new UserBulkForm([], 'user_bulk_form', $definition, $entity_manager, $language_manager);
+    $user_bulk_form = new UserBulkForm([], 'user_bulk_form', $definition, $entity_manager, $language_manager, $messenger);
     $user_bulk_form->init($executable, $display, $options);
 
     $this->assertAttributeEquals(array_slice($actions, 0, -1, TRUE), 'actions', $user_bulk_form);
diff --git a/core/modules/user/user.api.php b/core/modules/user/user.api.php
index 364dd1ac6343..823c08da6755 100644
--- a/core/modules/user/user.api.php
+++ b/core/modules/user/user.api.php
@@ -137,7 +137,14 @@ function hook_user_login($account) {
   $config = \Drupal::config('system.date');
   // If the user has a NULL time zone, notify them to set a time zone.
   if (!$account->getTimezone() && $config->get('timezone.user.configurable') && $config->get('timezone.user.warn')) {
-    drupal_set_message(t('Configure your <a href=":user-edit">account time zone setting</a>.', [':user-edit' => $account->url('edit-form', ['query' => \Drupal::destination()->getAsArray(), 'fragment' => 'edit-timezone'])]));
+    \Drupal::messenger()
+      ->addStatus(t('Configure your <a href=":user-edit">account time zone setting</a>.', [
+        ':user-edit' => $account->url('edit-form', [
+          'query' => \Drupal::destination()
+            ->getAsArray(),
+          'fragment' => 'edit-timezone',
+        ]),
+      ]));
   }
 }
 
diff --git a/core/modules/user/user.module b/core/modules/user/user.module
index cabe189e5a74..bc10222f9bd2 100644
--- a/core/modules/user/user.module
+++ b/core/modules/user/user.module
@@ -690,7 +690,7 @@ function user_cancel($edit, $uid, $method) {
   $account = User::load($uid);
 
   if (!$account) {
-    drupal_set_message(t('The user account %id does not exist.', ['%id' => $uid]), 'error');
+    \Drupal::messenger()->addError(t('The user account %id does not exist.', ['%id' => $uid]));
     \Drupal::logger('user')->error('Attempted to cancel non-existing user account: %id.', ['%id' => $uid]);
     return;
   }
@@ -761,7 +761,7 @@ function _user_cancel($edit, $account, $method) {
       }
       $account->block();
       $account->save();
-      drupal_set_message(t('%name has been disabled.', ['%name' => $account->getDisplayName()]));
+      \Drupal::messenger()->addStatus(t('%name has been disabled.', ['%name' => $account->getDisplayName()]));
       $logger->notice('Blocked user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
       break;
 
@@ -772,7 +772,7 @@ function _user_cancel($edit, $account, $method) {
         _user_mail_notify('status_canceled', $account);
       }
       $account->delete();
-      drupal_set_message(t('%name has been deleted.', ['%name' => $account->getDisplayName()]));
+      \Drupal::messenger()->addStatus(t('%name has been deleted.', ['%name' => $account->getDisplayName()]));
       $logger->notice('Deleted user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
       break;
   }
diff --git a/core/modules/views/src/Analyzer.php b/core/modules/views/src/Analyzer.php
index a6a8d56bf496..6e176293072e 100644
--- a/core/modules/views/src/Analyzer.php
+++ b/core/modules/views/src/Analyzer.php
@@ -52,7 +52,8 @@ public function getMessages(ViewExecutable $view) {
   /**
    * Formats the analyze result into a message string.
    *
-   * This is based upon the format of drupal_set_message which uses separate
+   * This is based upon the format of
+   * \Drupal\Core\Messenger\MessengerInterface::addMessage() which uses separate
    * boxes for "ok", "warning" and "error".
    */
   public function formatMessages(array $messages) {
diff --git a/core/modules/views/src/DisplayPluginCollection.php b/core/modules/views/src/DisplayPluginCollection.php
index 7c3c736fad97..74b69103d666 100644
--- a/core/modules/views/src/DisplayPluginCollection.php
+++ b/core/modules/views/src/DisplayPluginCollection.php
@@ -80,7 +80,7 @@ protected function initializePlugin($display_id) {
     // display plugin isn't found.
     catch (PluginException $e) {
       $message = $e->getMessage();
-      drupal_set_message(t('@message', ['@message' => $message]), 'warning');
+      \Drupal::messenger()->addWarning(t('@message', ['@message' => $message]));
     }
 
     // If no plugin instance has been created, return NULL.
diff --git a/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php b/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php
index 9911f61a0c87..c6d9137888d1 100644
--- a/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php
+++ b/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php
@@ -132,7 +132,7 @@ protected function initializeView($match = NULL, $match_operator = 'CONTAINS', $
     // Check that the view is valid and the display still exists.
     $this->view = Views::getView($view_name);
     if (!$this->view || !$this->view->access($display_name)) {
-      drupal_set_message(t('The reference view %view_name cannot be found.', ['%view_name' => $view_name]), 'warning');
+      \Drupal::messenger()->addWarning(t('The reference view %view_name cannot be found.', ['%view_name' => $view_name]));
       return FALSE;
     }
     $this->view->setDisplay($display_name);
diff --git a/core/modules/views/src/Plugin/views/area/View.php b/core/modules/views/src/Plugin/views/area/View.php
index 832e23185ddf..27c8d4875886 100644
--- a/core/modules/views/src/Plugin/views/area/View.php
+++ b/core/modules/views/src/Plugin/views/area/View.php
@@ -118,7 +118,7 @@ public function render($empty = FALSE) {
       // Check if the view is part of the parent views of this view
       $search = "$view_name:$display_id";
       if (in_array($search, $this->view->parent_views)) {
-        drupal_set_message(t("Recursion detected in view @view display @display.", ['@view' => $view_name, '@display' => $display_id]), 'error');
+        \Drupal::messenger()->addError(t("Recursion detected in view @view display @display.", ['@view' => $view_name, '@display' => $display_id]));
       }
       else {
         if (!empty($this->options['inherit_arguments']) && !empty($this->view->args)) {
diff --git a/core/modules/views/src/Plugin/views/field/BulkForm.php b/core/modules/views/src/Plugin/views/field/BulkForm.php
index a253fc3ad538..3ce092b98308 100644
--- a/core/modules/views/src/Plugin/views/field/BulkForm.php
+++ b/core/modules/views/src/Plugin/views/field/BulkForm.php
@@ -8,6 +8,7 @@
 use Drupal\Core\Entity\RevisionableInterface;
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\Core\Language\LanguageManagerInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Core\Routing\RedirectDestinationTrait;
 use Drupal\Core\TypedData\TranslatableInterface;
 use Drupal\views\Entity\Render\EntityTranslationRenderTrait;
@@ -56,6 +57,13 @@ class BulkForm extends FieldPluginBase implements CacheableDependencyInterface {
    */
   protected $languageManager;
 
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
   /**
    * Constructs a new BulkForm object.
    *
@@ -69,13 +77,18 @@ class BulkForm extends FieldPluginBase implements CacheableDependencyInterface {
    *   The entity manager.
    * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
    *   The language manager.
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   The messenger.
+   *
+   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
    */
-  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager) {
+  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager, MessengerInterface $messenger) {
     parent::__construct($configuration, $plugin_id, $plugin_definition);
 
     $this->entityManager = $entity_manager;
     $this->actionStorage = $entity_manager->getStorage('action');
     $this->languageManager = $language_manager;
+    $this->messenger = $messenger;
   }
 
   /**
@@ -87,7 +100,8 @@ public static function create(ContainerInterface $container, array $configuratio
       $plugin_id,
       $plugin_definition,
       $container->get('entity.manager'),
-      $container->get('language_manager')
+      $container->get('language_manager'),
+      $container->get('messenger')
     );
   }
 
@@ -356,11 +370,11 @@ public function viewsFormSubmit(&$form, FormStateInterface $form_state) {
 
         // Skip execution if the user did not have access.
         if (!$action->getPlugin()->access($entity, $this->view->getUser())) {
-          $this->drupalSetMessage($this->t('No access to execute %action on the @entity_type_label %entity_label.', [
+          $this->messenger->addError($this->t('No access to execute %action on the @entity_type_label %entity_label.', [
             '%action' => $action->label(),
             '@entity_type_label' => $entity->getEntityType()->getLabel(),
-            '%entity_label' => $entity->label()
-          ]), 'error');
+            '%entity_label' => $entity->label(),
+          ]));
           continue;
         }
 
@@ -382,7 +396,7 @@ public function viewsFormSubmit(&$form, FormStateInterface $form_state) {
         // Don't display the message unless there are some elements affected and
         // there is no confirmation form.
         if ($count) {
-          drupal_set_message($this->formatPlural($count, '%action was applied to @count item.', '%action was applied to @count items.', [
+          $this->messenger->addStatus($this->formatPlural($count, '%action was applied to @count item.', '%action was applied to @count items.', [
             '%action' => $action->label(),
           ]));
         }
@@ -426,13 +440,6 @@ public function clickSortable() {
     return FALSE;
   }
 
-  /**
-   * Wraps drupal_set_message().
-   */
-  protected function drupalSetMessage($message = NULL, $type = 'status', $repeat = FALSE) {
-    drupal_set_message($message, $type, $repeat);
-  }
-
   /**
    * Calculates a bulk form key.
    *
diff --git a/core/modules/views/src/Plugin/views/query/Sql.php b/core/modules/views/src/Plugin/views/query/Sql.php
index 09a754bb433e..512a99de8e64 100644
--- a/core/modules/views/src/Plugin/views/query/Sql.php
+++ b/core/modules/views/src/Plugin/views/query/Sql.php
@@ -8,6 +8,7 @@
 use Drupal\Core\Database\Query\Condition;
 use Drupal\Core\Entity\EntityTypeManagerInterface;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\views\Plugin\views\display\DisplayPluginBase;
 use Drupal\Core\Database\DatabaseExceptionWrapper;
 use Drupal\views\Plugin\views\join\JoinPluginBase;
@@ -130,6 +131,13 @@ class Sql extends QueryPluginBase {
    */
   protected $dateSql;
 
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface
+   */
+  protected $messenger;
+
   /**
    * Constructs a Sql object.
    *
@@ -143,21 +151,28 @@ class Sql extends QueryPluginBase {
    *   The entity type manager.
    * @param \Drupal\views\Plugin\views\query\DateSqlInterface $date_sql
    *   The database-specific date handler.
+   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+   *   The messenger.
    */
-  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, DateSqlInterface $date_sql) {
+  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, DateSqlInterface $date_sql, MessengerInterface $messenger) {
     parent::__construct($configuration, $plugin_id, $plugin_definition);
 
     $this->entityTypeManager = $entity_type_manager;
     $this->dateSql = $date_sql;
+    $this->messenger = $messenger;
   }
 
+  /**
+   * {@inheritdoc}
+   */
   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
     return new static(
       $configuration,
       $plugin_id,
       $plugin_definition,
       $container->get('entity_type.manager'),
-      $container->get('views.date_sql')
+      $container->get('views.date_sql'),
+      $container->get('messenger')
     );
   }
 
@@ -1522,7 +1537,7 @@ public function execute(ViewExecutable $view) {
       catch (DatabaseExceptionWrapper $e) {
         $view->result = [];
         if (!empty($view->live_preview)) {
-          drupal_set_message($e->getMessage(), 'error');
+          $this->messenger->addError($e->getMessage());
         }
         else {
           throw new DatabaseExceptionWrapper("Exception in {$view->storage->label()}[{$view->storage->id()}]: {$e->getMessage()}");
diff --git a/core/modules/views/tests/modules/views_test_data/src/Plugin/views/field/FieldFormButtonTest.php b/core/modules/views/tests/modules/views_test_data/src/Plugin/views/field/FieldFormButtonTest.php
index ee961ce69b80..a5d6b4dad947 100644
--- a/core/modules/views/tests/modules/views_test_data/src/Plugin/views/field/FieldFormButtonTest.php
+++ b/core/modules/views/tests/modules/views_test_data/src/Plugin/views/field/FieldFormButtonTest.php
@@ -3,6 +3,7 @@
 namespace Drupal\views_test_data\Plugin\views\field;
 
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Messenger\MessengerTrait;
 use Drupal\views\Plugin\views\field\FieldPluginBase;
 use Drupal\views\Plugin\views\field\UncacheableFieldHandlerTrait;
 use Drupal\views\ResultRow;
@@ -16,6 +17,7 @@
  */
 class FieldFormButtonTest extends FieldPluginBase {
 
+  use MessengerTrait;
   use UncacheableFieldHandlerTrait;
 
   /**
@@ -68,7 +70,7 @@ public function viewsFormSubmit(&$form, FormStateInterface $form_state) {
     if (!empty($triggering_element['#test_button'])) {
       $row_index = $triggering_element['#row_index'];
       $view_args = !empty($this->view->args) ? implode(', ', $this->view->args) : $this->t('no arguments');
-      drupal_set_message($this->t('The test button at row @row_index for @view_id (@display) View with args: @args was submitted.', [
+      $this->messenger()->addStatus($this->t('The test button at row @row_index for @view_id (@display) View with args: @args was submitted.', [
         '@display' => $this->view->current_display,
         '@view_id' => $this->view->id(),
         '@args' => $view_args,
diff --git a/core/modules/views/tests/modules/views_test_data/views_test_data.module b/core/modules/views/tests/modules/views_test_data/views_test_data.module
index cdb99cc100f6..64e0d44a069c 100644
--- a/core/modules/views/tests/modules/views_test_data/views_test_data.module
+++ b/core/modules/views/tests/modules/views_test_data/views_test_data.module
@@ -129,5 +129,5 @@ function views_test_data_test_pre_render_function($element) {
  * Implements hook_form_BASE_FORM_ID_alter().
  */
 function views_test_data_form_views_form_test_form_multiple_default_alter(&$form, FormStateInterface $form_state, $form_id) {
-  drupal_set_message(t('Test base form ID with Views forms and arguments.'));
+  \Drupal::messenger()->addStatus(t('Test base form ID with Views forms and arguments.'));
 }
diff --git a/core/modules/views/tests/src/Kernel/Handler/AreaMessagesTest.php b/core/modules/views/tests/src/Kernel/Handler/AreaMessagesTest.php
index 476551c9a8ff..a0bfb1cd53be 100644
--- a/core/modules/views/tests/src/Kernel/Handler/AreaMessagesTest.php
+++ b/core/modules/views/tests/src/Kernel/Handler/AreaMessagesTest.php
@@ -24,7 +24,7 @@ class AreaMessagesTest extends ViewsKernelTestBase {
    * Tests the messages area handler.
    */
   public function testMessageText() {
-    drupal_set_message('My drupal set message.');
+    \Drupal::messenger()->addStatus('My drupal set message.');
 
     $view = Views::getView('test_area_messages');
 
diff --git a/core/modules/views/tests/src/Unit/Plugin/query/SqlTest.php b/core/modules/views/tests/src/Unit/Plugin/query/SqlTest.php
index 80e8a334ef6a..60e11f21c9f3 100644
--- a/core/modules/views/tests/src/Unit/Plugin/query/SqlTest.php
+++ b/core/modules/views/tests/src/Unit/Plugin/query/SqlTest.php
@@ -6,6 +6,7 @@
 use Drupal\Core\Entity\EntityStorageInterface;
 use Drupal\Core\Entity\EntityType;
 use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Tests\UnitTestCase;
 use Drupal\views\Plugin\views\query\DateSqlInterface;
 use Drupal\views\Plugin\views\query\Sql;
@@ -31,8 +32,9 @@ public function testGetCacheTags() {
     $view = $this->prophesize('Drupal\views\ViewExecutable')->reveal();
     $entity_type_manager = $this->prophesize(EntityTypeManagerInterface::class);
     $date_sql = $this->prophesize(DateSqlInterface::class);
+    $messenger = $this->prophesize(MessengerInterface::class);
 
-    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal());
+    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal(), $messenger->reveal());
     $query->view = $view;
 
     $result = [];
@@ -78,8 +80,9 @@ public function testGetCacheMaxAge() {
     $view = $this->prophesize('Drupal\views\ViewExecutable')->reveal();
     $entity_type_manager = $this->prophesize(EntityTypeManagerInterface::class);
     $date_sql = $this->prophesize(DateSqlInterface::class);
+    $messenger = $this->prophesize(MessengerInterface::class);
 
-    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal());
+    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal(), $messenger->reveal());
     $query->view = $view;
 
     $view->result = [];
@@ -253,8 +256,9 @@ public function testLoadEntitiesWithEmptyResult() {
 
     $entity_type_manager = $this->setupEntityTypes();
     $date_sql = $this->prophesize(DateSqlInterface::class);
+    $messenger = $this->prophesize(MessengerInterface::class);
 
-    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal());
+    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal(), $messenger->reveal());
     $query->view = $view;
 
     $result = [];
@@ -282,8 +286,9 @@ public function testLoadEntitiesWithNoRelationshipAndNoRevision() {
     ];
     $entity_type_manager = $this->setupEntityTypes($entities);
     $date_sql = $this->prophesize(DateSqlInterface::class);
+    $messenger = $this->prophesize(MessengerInterface::class);
 
-    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal());
+    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal(), $messenger->reveal());
     $query->view = $view;
 
     $result = [];
@@ -346,8 +351,9 @@ public function testLoadEntitiesWithRelationship() {
     ];
     $entity_type_manager = $this->setupEntityTypes($entities);
     $date_sql = $this->prophesize(DateSqlInterface::class);
+    $messenger = $this->prophesize(MessengerInterface::class);
 
-    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal());
+    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal(), $messenger->reveal());
     $query->view = $view;
 
     $result = [];
@@ -401,8 +407,9 @@ public function testLoadEntitiesWithNonEntityRelationship() {
     ];
     $entity_type_manager = $this->setupEntityTypes($entities);
     $date_sql = $this->prophesize(DateSqlInterface::class);
+    $messenger = $this->prophesize(MessengerInterface::class);
 
-    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal());
+    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal(), $messenger->reveal());
     $query->view = $view;
 
     $result = [];
@@ -452,8 +459,9 @@ public function testLoadEntitiesWithRevision() {
     ];
     $entity_type_manager = $this->setupEntityTypes([], $entity_revisions);
     $date_sql = $this->prophesize(DateSqlInterface::class);
+    $messenger = $this->prophesize(MessengerInterface::class);
 
-    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal());
+    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal(), $messenger->reveal());
     $query->view = $view;
 
     $result = [];
@@ -506,8 +514,9 @@ public function testLoadEntitiesWithRevisionOfSameEntityType() {
     ];
     $entity_type_manager = $this->setupEntityTypes($entity, $entity_revisions);
     $date_sql = $this->prophesize(DateSqlInterface::class);
+    $messenger = $this->prophesize(MessengerInterface::class);
 
-    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal());
+    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal(), $messenger->reveal());
     $query->view = $view;
 
     $result = [];
@@ -564,8 +573,9 @@ public function testLoadEntitiesWithRelationshipAndRevision() {
     ];
     $entity_type_manager = $this->setupEntityTypes($entities, $entity_revisions);
     $date_sql = $this->prophesize(DateSqlInterface::class);
+    $messenger = $this->prophesize(MessengerInterface::class);
 
-    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal());
+    $query = new Sql([], 'sql', [], $entity_type_manager->reveal(), $date_sql->reveal(), $messenger->reveal());
     $query->view = $view;
 
     $result = [];
diff --git a/core/modules/views/views.api.php b/core/modules/views/views.api.php
index e6af1982f779..bf0fd7014e04 100644
--- a/core/modules/views/views.api.php
+++ b/core/modules/views/views.api.php
@@ -771,7 +771,7 @@ function hook_views_pre_execute(ViewExecutable $view) {
   $account = \Drupal::currentUser();
 
   if (count($view->query->tables) > 2 && $account->hasPermission('administer views')) {
-    drupal_set_message(t('The view %view may be heavy to execute.', ['%view' => $view->id()]), 'warning');
+    \Drupal::messenger()->addWarning(t('The view %view may be heavy to execute.', ['%view' => $view->id()]));
   }
 }
 
@@ -795,7 +795,7 @@ function hook_views_post_execute(ViewExecutable $view) {
   // (This action could be performed later in the execution process, but not
   // earlier.)
   if ($view->total_rows > 100) {
-    drupal_set_message(t('You have more than 100 hits. Use the filter settings to narrow down your list.'));
+    \Drupal::messenger()->addStatus(t('You have more than 100 hits. Use the filter settings to narrow down your list.'));
   }
 }
 
diff --git a/core/modules/views_ui/src/Form/AdvancedSettingsForm.php b/core/modules/views_ui/src/Form/AdvancedSettingsForm.php
index e4aa1c1f193d..534006cb3d0d 100644
--- a/core/modules/views_ui/src/Form/AdvancedSettingsForm.php
+++ b/core/modules/views_ui/src/Form/AdvancedSettingsForm.php
@@ -103,7 +103,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
    */
   public function cacheSubmit() {
     views_invalidate_cache();
-    drupal_set_message($this->t('The cache has been cleared.'));
+    $this->messenger()->addStatus($this->t('The cache has been cleared.'));
   }
 
 }
diff --git a/core/modules/views_ui/src/Form/BreakLockForm.php b/core/modules/views_ui/src/Form/BreakLockForm.php
index 6e93848802a1..91535750c3c6 100644
--- a/core/modules/views_ui/src/Form/BreakLockForm.php
+++ b/core/modules/views_ui/src/Form/BreakLockForm.php
@@ -110,7 +110,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
   public function submitForm(array &$form, FormStateInterface $form_state) {
     $this->tempStore->delete($this->entity->id());
     $form_state->setRedirectUrl($this->entity->urlInfo('edit-form'));
-    drupal_set_message($this->t('The lock has been broken and you may now edit this view.'));
+    $this->messenger()->addStatus($this->t('The lock has been broken and you may now edit this view.'));
   }
 
 }
diff --git a/core/modules/views_ui/src/ViewAddForm.php b/core/modules/views_ui/src/ViewAddForm.php
index e76621f2b36c..7ba511e7059a 100644
--- a/core/modules/views_ui/src/ViewAddForm.php
+++ b/core/modules/views_ui/src/ViewAddForm.php
@@ -184,12 +184,12 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     }
     // @todo Figure out whether it really makes sense to throw and catch exceptions on the wizard.
     catch (WizardException $e) {
-      drupal_set_message($e->getMessage(), 'error');
+      $this->messenger()->addError($e->getMessage());
       $form_state->setRedirect('entity.view.collection');
       return;
     }
     $this->entity->save();
-    drupal_set_message($this->t('The view %name has been saved.', ['%name' => $form_state->getValue('label')]));
+    $this->messenger()->addStatus($this->t('The view %name has been saved.', ['%name' => $form_state->getValue('label')]));
     $form_state->setRedirectUrl($this->entity->urlInfo('edit-form'));
   }
 
diff --git a/core/modules/views_ui/src/ViewEditForm.php b/core/modules/views_ui/src/ViewEditForm.php
index cea587e5ca0b..124795a2a4f5 100644
--- a/core/modules/views_ui/src/ViewEditForm.php
+++ b/core/modules/views_ui/src/ViewEditForm.php
@@ -325,7 +325,7 @@ public function save(array $form, FormStateInterface $form_state) {
 
     $view->save();
 
-    drupal_set_message($this->t('The view %name has been saved.', ['%name' => $view->label()]));
+    $this->messenger()->addStatus($this->t('The view %name has been saved.', ['%name' => $view->label()]));
 
     // Remove this view from cache so we can edit it properly.
     $this->tempStore->delete($view->id());
diff --git a/core/modules/views_ui/src/ViewUI.php b/core/modules/views_ui/src/ViewUI.php
index b2be658e24f4..beb5ffff475e 100644
--- a/core/modules/views_ui/src/ViewUI.php
+++ b/core/modules/views_ui/src/ViewUI.php
@@ -790,7 +790,7 @@ public function renderPreview($display_id, $args = []) {
     else {
       foreach ($errors as $display_errors) {
         foreach ($display_errors as $error) {
-          drupal_set_message($error, 'error');
+          \Drupal::messenger()->addError($error);
         }
       }
       $preview = ['#markup' => t('Unable to preview due to validation errors.')];
@@ -859,7 +859,7 @@ public function getFormProgress() {
    */
   public function cacheSet() {
     if ($this->isLocked()) {
-      drupal_set_message(t('Changes cannot be made to a locked view.'), 'error');
+      \Drupal::messenger()->addError(t('Changes cannot be made to a locked view.'));
       return;
     }
 
diff --git a/core/modules/workflows/src/Form/WorkflowAddForm.php b/core/modules/workflows/src/Form/WorkflowAddForm.php
index e3aac6fc4a49..47ad81212258 100644
--- a/core/modules/workflows/src/Form/WorkflowAddForm.php
+++ b/core/modules/workflows/src/Form/WorkflowAddForm.php
@@ -86,13 +86,13 @@ public function save(array $form, FormStateInterface $form_state) {
     $workflow = $this->entity;
     $return = $workflow->save();
     if (empty($workflow->getTypePlugin()->getStates())) {
-      drupal_set_message($this->t('Created the %label Workflow. In order for the workflow to be enabled there needs to be at least one state.', [
+      $this->messenger()->addStatus($this->t('Created the %label Workflow. In order for the workflow to be enabled there needs to be at least one state.', [
         '%label' => $workflow->label(),
       ]));
       $form_state->setRedirectUrl($workflow->toUrl('add-state-form'));
     }
     else {
-      drupal_set_message($this->t('Created the %label Workflow.', [
+      $this->messenger()->addStatus($this->t('Created the %label Workflow.', [
         '%label' => $workflow->label(),
       ]));
       $form_state->setRedirectUrl($workflow->toUrl('edit-form'));
diff --git a/core/modules/workflows/src/Form/WorkflowDeleteForm.php b/core/modules/workflows/src/Form/WorkflowDeleteForm.php
index 508205738db4..51a0bdd976a2 100644
--- a/core/modules/workflows/src/Form/WorkflowDeleteForm.php
+++ b/core/modules/workflows/src/Form/WorkflowDeleteForm.php
@@ -53,7 +53,7 @@ public function getConfirmText() {
   public function submitForm(array &$form, FormStateInterface $form_state) {
     $this->entity->delete();
 
-    drupal_set_message($this->t(
+    $this->messenger()->addStatus($this->t(
       'Workflow %label deleted.',
       ['%label' => $this->entity->label()]
     ));
diff --git a/core/modules/workflows/src/Form/WorkflowEditForm.php b/core/modules/workflows/src/Form/WorkflowEditForm.php
index 84af087fff47..676868d24211 100644
--- a/core/modules/workflows/src/Form/WorkflowEditForm.php
+++ b/core/modules/workflows/src/Form/WorkflowEditForm.php
@@ -103,12 +103,11 @@ public function form(array $form, FormStateInterface $form_state) {
 
     // Warn the user if there are no states.
     if (empty($states)) {
-      drupal_set_message(
+      $this->messenger()->addWarning(
         $this->t(
           'This workflow has no states and will be disabled until there is at least one, <a href=":add-state">add a new state.</a>',
           [':add-state' => $workflow->toUrl('add-state-form')->toString()]
-        ),
-        'warning'
+        )
       );
     }
 
@@ -261,7 +260,7 @@ public function save(array $form, FormStateInterface $form_state) {
     }
 
     $workflow->save();
-    drupal_set_message($this->t('Saved the %label Workflow.', ['%label' => $workflow->label()]));
+    $this->messenger()->addStatus($this->t('Saved the %label Workflow.', ['%label' => $workflow->label()]));
   }
 
   /**
diff --git a/core/modules/workflows/src/Form/WorkflowStateAddForm.php b/core/modules/workflows/src/Form/WorkflowStateAddForm.php
index 4b5f72339553..5eb1b9a4c768 100644
--- a/core/modules/workflows/src/Form/WorkflowStateAddForm.php
+++ b/core/modules/workflows/src/Form/WorkflowStateAddForm.php
@@ -162,7 +162,7 @@ public function save(array $form, FormStateInterface $form_state) {
     }
 
     $workflow->save();
-    drupal_set_message($this->t('Created %label state.', [
+    $this->messenger()->addStatus($this->t('Created %label state.', [
       '%label' => $workflow->getTypePlugin()->getState($form_state->getValue('id'))->label(),
     ]));
     $form_state->setRedirectUrl($workflow->toUrl('edit-form'));
diff --git a/core/modules/workflows/src/Form/WorkflowStateDeleteForm.php b/core/modules/workflows/src/Form/WorkflowStateDeleteForm.php
index 14d1bbe017b3..fd0fa43f2123 100644
--- a/core/modules/workflows/src/Form/WorkflowStateDeleteForm.php
+++ b/core/modules/workflows/src/Form/WorkflowStateDeleteForm.php
@@ -98,7 +98,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       ->deleteState($this->stateId);
     $this->workflow->save();
 
-    drupal_set_message($this->t(
+    $this->messenger()->addStatus($this->t(
       'State %label deleted.',
       ['%label' => $workflow_label]
     ));
diff --git a/core/modules/workflows/src/Form/WorkflowStateEditForm.php b/core/modules/workflows/src/Form/WorkflowStateEditForm.php
index bba3b11c1349..4fe5f5e55753 100644
--- a/core/modules/workflows/src/Form/WorkflowStateEditForm.php
+++ b/core/modules/workflows/src/Form/WorkflowStateEditForm.php
@@ -201,7 +201,7 @@ public function save(array $form, FormStateInterface $form_state) {
     }
 
     $workflow->save();
-    drupal_set_message($this->t('Saved %label state.', [
+    $this->messenger()->addStatus($this->t('Saved %label state.', [
       '%label' => $workflow->getTypePlugin()->getState($this->stateId)->label(),
     ]));
     $form_state->setRedirectUrl($workflow->toUrl('edit-form'));
diff --git a/core/modules/workflows/src/Form/WorkflowTransitionAddForm.php b/core/modules/workflows/src/Form/WorkflowTransitionAddForm.php
index 1ac8de54b405..87aea537a1cf 100644
--- a/core/modules/workflows/src/Form/WorkflowTransitionAddForm.php
+++ b/core/modules/workflows/src/Form/WorkflowTransitionAddForm.php
@@ -188,7 +188,7 @@ public function save(array $form, FormStateInterface $form_state) {
     }
 
     $workflow->save();
-    drupal_set_message($this->t('Created %label transition.', [
+    $this->messenger()->addStatus($this->t('Created %label transition.', [
       '%label' => $form_state->getValue('label'),
     ]));
     $form_state->setRedirectUrl($workflow->toUrl('edit-form'));
diff --git a/core/modules/workflows/src/Form/WorkflowTransitionDeleteForm.php b/core/modules/workflows/src/Form/WorkflowTransitionDeleteForm.php
index 63479626d4f8..1fee5d415791 100644
--- a/core/modules/workflows/src/Form/WorkflowTransitionDeleteForm.php
+++ b/core/modules/workflows/src/Form/WorkflowTransitionDeleteForm.php
@@ -98,7 +98,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
       ->deleteTransition($this->transition->id());
     $this->workflow->save();
 
-    drupal_set_message($this->t('%transition transition deleted.', ['%transition' => $this->transition->label()]));
+    $this->messenger()->addStatus($this->t('%transition transition deleted.', ['%transition' => $this->transition->label()]));
     $form_state->setRedirectUrl($this->getCancelUrl());
   }
 
diff --git a/core/modules/workflows/src/Form/WorkflowTransitionEditForm.php b/core/modules/workflows/src/Form/WorkflowTransitionEditForm.php
index 9d3a2231d630..ac1552ecdd0f 100644
--- a/core/modules/workflows/src/Form/WorkflowTransitionEditForm.php
+++ b/core/modules/workflows/src/Form/WorkflowTransitionEditForm.php
@@ -198,7 +198,7 @@ public function save(array $form, FormStateInterface $form_state) {
     }
 
     $workflow->save();
-    drupal_set_message($this->t('Saved %label transition.', [
+    $this->messenger()->addStatus($this->t('Saved %label transition.', [
       '%label' => $workflow->getTypePlugin()->getTransition($this->transitionId)->label(),
     ]));
     $form_state->setRedirectUrl($workflow->toUrl('edit-form'));
diff --git a/core/tests/Drupal/Tests/Core/Form/FormErrorHandlerTest.php b/core/tests/Drupal/Tests/Core/Form/FormErrorHandlerTest.php
index 8e2fc0d2b729..ba5d5e8f3cd9 100644
--- a/core/tests/Drupal/Tests/Core/Form/FormErrorHandlerTest.php
+++ b/core/tests/Drupal/Tests/Core/Form/FormErrorHandlerTest.php
@@ -3,6 +3,7 @@
 namespace Drupal\Tests\Core\Form;
 
 use Drupal\Core\Form\FormState;
+use Drupal\Core\Messenger\MessengerInterface;
 use Drupal\Tests\UnitTestCase;
 
 /**
@@ -11,32 +12,59 @@
  */
 class FormErrorHandlerTest extends UnitTestCase {
 
+  /**
+   * The form error handler.
+   *
+   * @var \Drupal\Core\Form\FormErrorHandler|\PHPUnit_Framework_MockObject_MockObject
+   */
+  protected $formErrorHandler;
+
+  /**
+   * The messenger.
+   *
+   * @var \Drupal\Core\Messenger\MessengerInterface|\PHPUnit_Framework_MockObject_MockObject
+   */
+  protected $messenger;
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function setUp() {
+    parent::setUp();
+
+    $this->messenger = $this->createMock(MessengerInterface::class);
+
+    $this->formErrorHandler = $this->getMockBuilder('Drupal\Core\Form\FormErrorHandler')
+      ->setMethods(['messenger'])
+      ->getMock();
+
+    $this->formErrorHandler->expects($this->atLeastOnce())
+      ->method('messenger')
+      ->willReturn($this->messenger);
+  }
+
   /**
    * @covers ::handleFormErrors
    * @covers ::displayErrorMessages
    */
   public function testDisplayErrorMessages() {
-    $form_error_handler = $this->getMockBuilder('Drupal\Core\Form\FormErrorHandler')
-      ->setMethods(['drupalSetMessage'])
-      ->getMock();
-
-    $form_error_handler->expects($this->at(0))
-      ->method('drupalSetMessage')
+    $this->messenger->expects($this->at(0))
+      ->method('addMessage')
       ->with('invalid', 'error');
-    $form_error_handler->expects($this->at(1))
-      ->method('drupalSetMessage')
+    $this->messenger->expects($this->at(1))
+      ->method('addMessage')
       ->with('invalid', 'error');
-    $form_error_handler->expects($this->at(2))
-      ->method('drupalSetMessage')
+    $this->messenger->expects($this->at(2))
+      ->method('addMessage')
       ->with('invalid', 'error');
-    $form_error_handler->expects($this->at(3))
-      ->method('drupalSetMessage')
+    $this->messenger->expects($this->at(3))
+      ->method('addMessage')
       ->with('no title given', 'error');
-    $form_error_handler->expects($this->at(4))
-      ->method('drupalSetMessage')
+    $this->messenger->expects($this->at(4))
+      ->method('addMessage')
       ->with('element is invisible', 'error');
-    $form_error_handler->expects($this->at(5))
-      ->method('drupalSetMessage')
+    $this->messenger->expects($this->at(5))
+      ->method('addMessage')
       ->with('this missing element is invalid', 'error');
 
     $form = [
@@ -88,7 +116,7 @@ public function testDisplayErrorMessages() {
     $form_state->setErrorByName('test5', 'no title given');
     $form_state->setErrorByName('test6', 'element is invisible');
     $form_state->setErrorByName('missing_element', 'this missing element is invalid');
-    $form_error_handler->handleFormErrors($form, $form_state);
+    $this->formErrorHandler->handleFormErrors($form, $form_state);
     $this->assertSame('invalid', $form['test1']['#errors']);
   }
 
@@ -97,10 +125,6 @@ public function testDisplayErrorMessages() {
    * @covers ::setElementErrorsFromFormState
    */
   public function testSetElementErrorsFromFormState() {
-    $form_error_handler = $this->getMockBuilder('Drupal\Core\Form\FormErrorHandler')
-      ->setMethods(['drupalSetMessage'])
-      ->getMock();
-
     $form = [
       '#parents' => [],
       '#array_parents' => [],
@@ -176,7 +200,7 @@ public function testSetElementErrorsFromFormState() {
     $form_state->setErrorByName('grouping_test2', 'invalid');
     $form_state->setErrorByName('fieldset][nested_test', 'invalid');
     $form_state->setErrorByName('fieldset][nested_test2', 'invalid2');
-    $form_error_handler->handleFormErrors($form, $form_state);
+    $this->formErrorHandler->handleFormErrors($form, $form_state);
     $this->assertSame('invalid', $form['test']['#errors']);
     $this->assertSame([
       'grouping_test' => 'invalid',
-- 
GitLab