From 9be30ef535243ac09333a137a0609924ce6f866a Mon Sep 17 00:00:00 2001 From: Alex Pott <alex.a.pott@googlemail.com> Date: Wed, 20 Aug 2014 16:26:18 +0100 Subject: [PATCH] Issue #2271251 by ParisLiakos, undertext, JeroenT, StevenPatz, tim.plunkett: Remove usages of watchdog() from non-form and non-controllers. --- core/core.services.yml | 18 +++++++--- .../Core/Controller/ExceptionController.php | 20 ++++++++--- core/lib/Drupal/Core/Cron.php | 17 +++++++-- .../UpdateServiceProvider.php | 1 + core/lib/Drupal/Core/DrupalKernel.php | 2 +- .../Drupal/Core/Extension/ModuleHandler.php | 4 +-- .../Drupal/Core/Extension/ThemeHandler.php | 15 ++++++-- core/lib/Drupal/Core/Form/FormValidator.php | 24 +++++++------ .../aggregator/aggregator.services.yml | 7 +++- core/modules/aggregator/src/ItemsImporter.php | 17 +++++++-- core/modules/config/src/Form/ConfigSync.php | 2 +- .../src/Tests/Rest/DbLogResourceTest.php | 2 +- .../src/Tests/Views/ViewsIntegrationTest.php | 18 +++++----- core/modules/locale/src/PoDatabaseWriter.php | 2 +- core/modules/migrate/src/MigrateMessage.php | 3 +- core/modules/rest/rest.services.yml | 7 +++- .../rest/src/Routing/ResourceRoutes.php | 17 +++++++-- .../system/src/Access/CronAccessCheck.php | 4 +-- .../system/src/Tests/Pager/PagerTest.php | 3 +- .../src/Plugin/views/display/DisplayTest.php | 2 +- .../Controller/ExceptionControllerTest.php | 3 +- .../Tests/Core/Extension/ThemeHandlerTest.php | 3 +- .../Tests/Core/Form/FormBuilderTest.php | 4 --- .../Drupal/Tests/Core/Form/FormTestBase.php | 8 ++++- .../Tests/Core/Form/FormValidatorTest.php | 35 ++++++++----------- 25 files changed, 161 insertions(+), 77 deletions(-) diff --git a/core/core.services.yml b/core/core.services.yml index 3254f844a0be..d6263c74312c 100644 --- a/core/core.services.yml +++ b/core/core.services.yml @@ -136,7 +136,7 @@ services: arguments: ['@typed_data_manager'] cron: class: Drupal\Core\Cron - arguments: ['@module_handler', '@lock', '@queue', '@state', '@current_user', '@session_manager'] + arguments: ['@module_handler', '@lock', '@queue', '@state', '@current_user', '@session_manager', '@logger.channel.cron'] diff.formatter: class: Drupal\Core\Diff\DiffFormatter arguments: ['@config.factory'] @@ -150,7 +150,7 @@ services: arguments: ['@form_validator', '@form_submitter', '@module_handler', '@keyvalue.expirable', '@event_dispatcher', '@request_stack', '@class_resolver', '@?csrf_token', '@?http_kernel'] form_validator: class: Drupal\Core\Form\FormValidator - arguments: ['@request_stack', '@string_translation', '@csrf_token'] + arguments: ['@request_stack', '@string_translation', '@csrf_token', '@logger.channel.form'] form_submitter: class: Drupal\Core\Form\FormSubmitter arguments: ['@request_stack', '@url_generator'] @@ -183,6 +183,16 @@ services: factory_method: get factory_service: logger.factory arguments: ['image'] + logger.channel.cron: + class: Drupal\Core\Logger\LoggerChannel + factory_method: get + factory_service: logger.factory + arguments: ['cron'] + logger.channel.form: + class: Drupal\Core\Logger\LoggerChannel + factory_method: get + factory_service: logger.factory + arguments: ['form'] logger.log_message_parser: class: Drupal\Core\Logger\LogMessageParser @@ -254,7 +264,7 @@ services: arguments: ['%container.modules%', '@cache.bootstrap'] theme_handler: class: Drupal\Core\Extension\ThemeHandler - arguments: ['@config.factory', '@module_handler', '@state', '@info_parser', '@asset.css.collection_optimizer', '@config.installer', '@router.builder'] + arguments: ['@config.factory', '@module_handler', '@state', '@info_parser', '@logger.channel.default', '@asset.css.collection_optimizer', '@config.installer', '@router.builder'] entity.manager: class: Drupal\Core\Entity\EntityManager arguments: ['@container.namespaces', '@module_handler', '@cache.discovery', '@language_manager', '@string_translation', '@class_resolver', '@typed_data_manager'] @@ -698,7 +708,7 @@ services: arguments: ['@config.manager', '@config.storage', '@config.storage.snapshot'] exception_controller: class: Drupal\Core\Controller\ExceptionController - arguments: ['@content_negotiation', '@title_resolver', '@html_page_renderer', '@html_fragment_renderer', '@string_translation', '@url_generator'] + arguments: ['@content_negotiation', '@title_resolver', '@html_page_renderer', '@html_fragment_renderer', '@string_translation', '@url_generator', '@logger.factory'] calls: - [setContainer, ['@service_container']] exception_listener: diff --git a/core/lib/Drupal/Core/Controller/ExceptionController.php b/core/lib/Drupal/Core/Controller/ExceptionController.php index dbd227f13a98..69a477b4ccc0 100644 --- a/core/lib/Drupal/Core/Controller/ExceptionController.php +++ b/core/lib/Drupal/Core/Controller/ExceptionController.php @@ -7,6 +7,7 @@ namespace Drupal\Core\Controller; +use Drupal\Core\Logger\LoggerChannelFactoryInterface; use Drupal\Core\Page\DefaultHtmlPageRenderer; use Drupal\Core\Page\HtmlFragmentRendererInterface; use Drupal\Core\Page\HtmlPageRendererInterface; @@ -59,6 +60,13 @@ class ExceptionController extends HtmlControllerBase implements ContainerAwareIn */ protected $fragmentRenderer; + /** + * The logger factory service. + * + * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface + */ + protected $loggerFactory; + /** * Constructor. * @@ -74,13 +82,17 @@ class ExceptionController extends HtmlControllerBase implements ContainerAwareIn * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation * The url generator. * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator + * The URL generator. + * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory + * The logger factory. */ - public function __construct(ContentNegotiation $negotiation, TitleResolverInterface $title_resolver, HtmlPageRendererInterface $renderer, HtmlFragmentRendererInterface $fragment_renderer, TranslationInterface $string_translation, UrlGeneratorInterface $url_generator) { + public function __construct(ContentNegotiation $negotiation, TitleResolverInterface $title_resolver, HtmlPageRendererInterface $renderer, HtmlFragmentRendererInterface $fragment_renderer, TranslationInterface $string_translation, UrlGeneratorInterface $url_generator, LoggerChannelFactoryInterface $logger_factory) { parent::__construct($title_resolver, $url_generator); $this->negotiation = $negotiation; $this->htmlPageRenderer = $renderer; $this->fragmentRenderer = $fragment_renderer; $this->stringTranslation = $string_translation; + $this->loggerFactory = $logger_factory; } /** @@ -146,7 +158,7 @@ public function on403Html(FlattenException $exception, Request $request) { // @todo Remove dependency on the internal _system_path attribute: // https://www.drupal.org/node/2293523. $system_path = $request->attributes->get('_system_path'); - watchdog('access denied', $system_path, array(), WATCHDOG_WARNING); + $this->loggerFactory->get('access denied')->warning($system_path); $system_config = $this->container->get('config.factory')->get('system.site'); $path = $this->container->get('path.alias_manager')->getPathByAlias($system_config->get('page.403')); @@ -188,7 +200,7 @@ public function on403Html(FlattenException $exception, Request $request) { * A response object. */ public function on404Html(FlattenException $exception, Request $request) { - watchdog('page not found', String::checkPlain($request->attributes->get('_system_path')), array(), WATCHDOG_WARNING); + $this->loggerFactory->get('page not found')->warning(String::checkPlain($request->attributes->get('_system_path'))); // Check for and return a fast 404 page if configured. $config = \Drupal::config('system.performance'); @@ -276,7 +288,7 @@ public function on500Html(FlattenException $exception, Request $request) { $number++; } - watchdog('php', '%type: !message in %function (line %line of %file).', $error, $error['severity_level']); + $this->loggerFactory->get('php')->log($error['severity_level'], '%type: !message in %function (line %line of %file).', $error); // Display the message if the current error reporting level allows this type // of message to be displayed, and unconditionnaly in update.php. diff --git a/core/lib/Drupal/Core/Cron.php b/core/lib/Drupal/Core/Cron.php index b639f5c43636..dddf38dedd74 100644 --- a/core/lib/Drupal/Core/Cron.php +++ b/core/lib/Drupal/Core/Cron.php @@ -15,6 +15,7 @@ use Drupal\Core\Session\AnonymousUserSession; use Drupal\Core\Session\SessionManagerInterface; use Drupal\Core\Queue\SuspendQueueException; +use Psr\Log\LoggerInterface; /** * The Drupal core Cron service. @@ -63,6 +64,13 @@ class Cron implements CronInterface { */ protected $sessionManager; + /** + * A logger instance. + * + * @var \Psr\Log\LoggerInterface + */ + protected $logger; + /** * Constructs a cron object. * @@ -78,14 +86,17 @@ class Cron implements CronInterface { * The current user. * @param \Drupal\Core\Session\SessionManagerInterface $session_manager * The session manager. + * @param \Psr\Log\LoggerInterface $logger + * A logger instance. */ - public function __construct(ModuleHandlerInterface $module_handler, LockBackendInterface $lock, QueueFactory $queue_factory, StateInterface $state, AccountProxyInterface $current_user, SessionManagerInterface $session_manager) { + public function __construct(ModuleHandlerInterface $module_handler, LockBackendInterface $lock, QueueFactory $queue_factory, StateInterface $state, AccountProxyInterface $current_user, SessionManagerInterface $session_manager, LoggerInterface $logger) { $this->moduleHandler = $module_handler; $this->lock = $lock; $this->queueFactory = $queue_factory; $this->state = $state; $this->currentUser = $current_user; $this->sessionManager = $session_manager; + $this->logger = $logger; } /** @@ -112,7 +123,7 @@ public function run() { // Try to acquire cron lock. if (!$this->lock->acquire('cron', 240.0)) { // Cron is still running normally. - watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING); + $this->logger->warning('Attempting to re-run cron while it is already running.'); } else { $this->invokeCronHandlers(); @@ -143,7 +154,7 @@ public function run() { protected function setCronLastTime() { // Record cron time. $this->state->set('system.cron_last', REQUEST_TIME); - watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE); + $this->logger->notice('Cron run completed.'); } /** diff --git a/core/lib/Drupal/Core/DependencyInjection/UpdateServiceProvider.php b/core/lib/Drupal/Core/DependencyInjection/UpdateServiceProvider.php index ec30db020ef9..d8a40aa4a913 100644 --- a/core/lib/Drupal/Core/DependencyInjection/UpdateServiceProvider.php +++ b/core/lib/Drupal/Core/DependencyInjection/UpdateServiceProvider.php @@ -43,6 +43,7 @@ public function register(ContainerBuilder $container) { ->addArgument(new Reference('module_handler')) ->addArgument(new Reference('state')) ->addArgument(new Reference('info_parser')) + ->addArgument(new Reference('logger.channel.default')) ->addArgument(new Reference('asset.css.collection_optimizer')); } } diff --git a/core/lib/Drupal/Core/DrupalKernel.php b/core/lib/Drupal/Core/DrupalKernel.php index 2551a4d02048..7b69341e63d2 100644 --- a/core/lib/Drupal/Core/DrupalKernel.php +++ b/core/lib/Drupal/Core/DrupalKernel.php @@ -404,7 +404,7 @@ public function shutdown() { */ public function getContainer() { if ($this->containerNeedsDumping && !$this->dumpDrupalContainer($this->container, static::CONTAINER_BASE_CLASS)) { - watchdog('DrupalKernel', 'Container cannot be written to disk'); + $this->container->get('logger.factory')->get('DrupalKernel')->notice('Container cannot be written to disk'); } return $this->container; } diff --git a/core/lib/Drupal/Core/Extension/ModuleHandler.php b/core/lib/Drupal/Core/Extension/ModuleHandler.php index 6270c8ef780a..4bb2efa6bfe1 100644 --- a/core/lib/Drupal/Core/Extension/ModuleHandler.php +++ b/core/lib/Drupal/Core/Extension/ModuleHandler.php @@ -901,7 +901,7 @@ public function install(array $module_list, $enable_dependencies = TRUE) { $this->invoke($module, 'install'); // Record the fact that it was installed. - watchdog('system', '%module module installed.', array('%module' => $module), WATCHDOG_INFO); + \Drupal::logger('system')->info('%module module installed.', array('%module' => $module)); } } @@ -1028,7 +1028,7 @@ public function uninstall(array $module_list, $uninstall_dependents = TRUE) { // @see https://drupal.org/node/2208429 \Drupal::service('theme_handler')->refreshInfo(); - watchdog('system', '%module module uninstalled.', array('%module' => $module), WATCHDOG_INFO); + \Drupal::logger('system')->info('%module module uninstalled.', array('%module' => $module)); $schema_store->delete($module); } diff --git a/core/lib/Drupal/Core/Extension/ThemeHandler.php b/core/lib/Drupal/Core/Extension/ThemeHandler.php index e1b8cbfdcbf2..c5f71393e765 100644 --- a/core/lib/Drupal/Core/Extension/ThemeHandler.php +++ b/core/lib/Drupal/Core/Extension/ThemeHandler.php @@ -14,6 +14,7 @@ use Drupal\Core\Config\ConfigInstallerInterface; use Drupal\Core\State\StateInterface; use Drupal\Core\Routing\RouteBuilder; +use Psr\Log\LoggerInterface; /** * Default theme handler using the config system for enabled/disabled themes. @@ -79,6 +80,13 @@ class ThemeHandler implements ThemeHandlerInterface { */ protected $infoParser; + /** + * A logger instance. + * + * @var \Psr\Log\LoggerInterface + */ + protected $logger; + /** * The route builder to rebuild the routes if a theme is enabled. * @@ -113,6 +121,8 @@ class ThemeHandler implements ThemeHandlerInterface { * The info parser to parse the theme.info.yml files. * @param \Drupal\Core\Asset\AssetCollectionOptimizerInterface $css_collection_optimizer * The CSS asset collection optimizer service. + * @param \Psr\Log\LoggerInterface $logger + * A logger instance. * @param \Drupal\Core\Config\ConfigInstallerInterface $config_installer * (optional) The config installer to install configuration. This optional * to allow the theme handler to work before Drupal is installed and has a @@ -122,11 +132,12 @@ class ThemeHandler implements ThemeHandlerInterface { * @param \Drupal\Core\Extension\ExtensionDiscovery $extension_discovery * (optional) A extension discovery instance (for unit tests). */ - public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, StateInterface $state, InfoParserInterface $info_parser, AssetCollectionOptimizerInterface $css_collection_optimizer = NULL, ConfigInstallerInterface $config_installer = NULL, RouteBuilder $route_builder = NULL, ExtensionDiscovery $extension_discovery = NULL) { + public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, StateInterface $state, InfoParserInterface $info_parser,LoggerInterface $logger, AssetCollectionOptimizerInterface $css_collection_optimizer = NULL, ConfigInstallerInterface $config_installer = NULL, RouteBuilder $route_builder = NULL, ExtensionDiscovery $extension_discovery = NULL) { $this->configFactory = $config_factory; $this->moduleHandler = $module_handler; $this->state = $state; $this->infoParser = $info_parser; + $this->logger = $logger; $this->cssCollectionOptimizer = $css_collection_optimizer; $this->configInstaller = $config_installer; $this->routeBuilder = $route_builder; @@ -268,7 +279,7 @@ public function enable(array $theme_list, $enable_dependencies = TRUE) { $themes_enabled[] = $key; // Record the fact that it was enabled. - watchdog('system', '%theme theme enabled.', array('%theme' => $key), WATCHDOG_INFO); + $this->logger->info('%theme theme enabled.', array('%theme' => $key)); } $this->cssCollectionOptimizer->deleteAll(); diff --git a/core/lib/Drupal/Core/Form/FormValidator.php b/core/lib/Drupal/Core/Form/FormValidator.php index 830ed561471e..de48d4c0ee6a 100644 --- a/core/lib/Drupal/Core/Form/FormValidator.php +++ b/core/lib/Drupal/Core/Form/FormValidator.php @@ -13,6 +13,7 @@ use Drupal\Core\Render\Element; use Drupal\Core\StringTranslation\StringTranslationTrait; use Drupal\Core\StringTranslation\TranslationInterface; +use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\RequestStack; /** @@ -36,6 +37,13 @@ class FormValidator implements FormValidatorInterface { */ protected $requestStack; + /** + * A logger instance. + * + * @var \Psr\Log\LoggerInterface + */ + protected $logger; + /** * Constructs a new FormValidator. * @@ -45,11 +53,14 @@ class FormValidator implements FormValidatorInterface { * The string translation service. * @param \Drupal\Core\Access\CsrfTokenGenerator $csrf_token * The CSRF token generator. + * @param \Psr\Log\LoggerInterface $logger + * A logger instance. */ - public function __construct(RequestStack $request_stack, TranslationInterface $string_translation, CsrfTokenGenerator $csrf_token) { + public function __construct(RequestStack $request_stack, TranslationInterface $string_translation, CsrfTokenGenerator $csrf_token, LoggerInterface $logger) { $this->requestStack = $request_stack; $this->stringTranslation = $string_translation; $this->csrfToken = $csrf_token; + $this->logger = $logger; } /** @@ -319,7 +330,7 @@ protected function performRequiredValidation(&$elements, FormStateInterface &$fo foreach ($value as $v) { if (!isset($options[$v])) { $form_state->setError($elements, $this->t('An illegal choice has been detected. Please contact the site administrator.')); - $this->watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR); + $this->logger->error('Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'])); } } } @@ -338,7 +349,7 @@ protected function performRequiredValidation(&$elements, FormStateInterface &$fo } elseif (!isset($options[$elements['#value']])) { $form_state->setError($elements, $this->t('An illegal choice has been detected. Please contact the site administrator.')); - $this->watchdog('form', 'Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR); + $this->logger->error('Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'])); } } } @@ -409,11 +420,4 @@ protected function setElementErrorsFromFormState(array &$elements, FormStateInte $elements['#errors'] = $form_state->getError($elements); } - /** - * Wraps watchdog(). - */ - protected function watchdog($type, $message, array $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL) { - watchdog($type, $message, $variables, $severity, $link); - } - } diff --git a/core/modules/aggregator/aggregator.services.yml b/core/modules/aggregator/aggregator.services.yml index 930b9451089e..8747737f264f 100644 --- a/core/modules/aggregator/aggregator.services.yml +++ b/core/modules/aggregator/aggregator.services.yml @@ -10,4 +10,9 @@ services: arguments: [processor, '@container.namespaces', '@cache.discovery', '@module_handler'] aggregator.items.importer: class: Drupal\aggregator\ItemsImporter - arguments: ['@config.factory', '@plugin.manager.aggregator.fetcher', '@plugin.manager.aggregator.parser', '@plugin.manager.aggregator.processor'] + arguments: ['@config.factory', '@plugin.manager.aggregator.fetcher', '@plugin.manager.aggregator.parser', '@plugin.manager.aggregator.processor', '@logger.channel.aggregator'] + logger.channel.aggregator: + class: Drupal\Core\Logger\LoggerChannel + factory_method: get + factory_service: logger.factory + arguments: ['aggregator'] diff --git a/core/modules/aggregator/src/ItemsImporter.php b/core/modules/aggregator/src/ItemsImporter.php index ac3277dfc35b..af193253f399 100644 --- a/core/modules/aggregator/src/ItemsImporter.php +++ b/core/modules/aggregator/src/ItemsImporter.php @@ -10,6 +10,7 @@ use Drupal\aggregator\Plugin\AggregatorPluginManager; use Drupal\Component\Plugin\Exception\PluginException; use Drupal\Core\Config\ConfigFactoryInterface; +use Psr\Log\LoggerInterface; /** * Defines an importer of aggregator items. @@ -44,6 +45,13 @@ class ItemsImporter implements ItemsImporterInterface { */ protected $config; + /** + * A logger instance. + * + * @var \Psr\Log\LoggerInterface + */ + protected $logger; + /** * Constructs an Importer object. * @@ -55,12 +63,15 @@ class ItemsImporter implements ItemsImporterInterface { * The aggregator parser plugin manager. * @param \Drupal\aggregator\Plugin\AggregatorPluginManager $processor_manager * The aggregator processor plugin manager. + * @param \Psr\Log\LoggerInterface $logger + * A logger instance. */ - public function __construct(ConfigFactoryInterface $config_factory, AggregatorPluginManager $fetcher_manager, AggregatorPluginManager $parser_manager, AggregatorPluginManager $processor_manager) { + public function __construct(ConfigFactoryInterface $config_factory, AggregatorPluginManager $fetcher_manager, AggregatorPluginManager $parser_manager, AggregatorPluginManager $processor_manager, LoggerInterface $logger) { $this->fetcherManager = $fetcher_manager; $this->processorManager = $processor_manager; $this->parserManager = $parser_manager; $this->config = $config_factory->get('aggregator.settings'); + $this->logger = $logger; } /** @@ -118,10 +129,10 @@ public function refresh(FeedInterface $feed) { // Log if feed URL has changed. if ($feed->getUrl() != $feed_url) { - watchdog('aggregator', 'Updated URL for feed %title to %url.', array('%title' => $feed->label(), '%url' => $feed->getUrl())); + $this->logger->notice('Updated URL for feed %title to %url.', array('%title' => $feed->label(), '%url' => $feed->getUrl())); } - watchdog('aggregator', 'There is new syndicated content from %site.', array('%site' => $feed->label())); + $this->logger->notice('There is new syndicated content from %site.', array('%site' => $feed->label())); // If there are items on the feed, let enabled processors process them. if (!empty($feed->items)) { diff --git a/core/modules/config/src/Form/ConfigSync.php b/core/modules/config/src/Form/ConfigSync.php index a93c0ff2d757..70c0c7300853 100644 --- a/core/modules/config/src/Form/ConfigSync.php +++ b/core/modules/config/src/Form/ConfigSync.php @@ -349,7 +349,7 @@ public static function finishBatch($success, $results, $operations) { if (!empty($results['errors'])) { foreach ($results['errors'] as $error) { drupal_set_message($error, 'error'); - watchdog('config_sync', $error, array(), WATCHDOG_ERROR); + \Drupal::logger('config_sync')->error($error); } drupal_set_message(\Drupal::translation()->translate('The configuration was imported with errors.'), 'warning'); } diff --git a/core/modules/dblog/src/Tests/Rest/DbLogResourceTest.php b/core/modules/dblog/src/Tests/Rest/DbLogResourceTest.php index 2a4deb3940b6..25c7a901bde4 100644 --- a/core/modules/dblog/src/Tests/Rest/DbLogResourceTest.php +++ b/core/modules/dblog/src/Tests/Rest/DbLogResourceTest.php @@ -35,7 +35,7 @@ protected function setUp() { */ public function testWatchdog() { // Write a log message to the DB. - watchdog('rest', 'Test message'); + $this->container->get('logger.channel.rest')->notice('Test message'); // Get the ID of the written message. $id = db_query_range("SELECT wid FROM {watchdog} WHERE type = :type ORDER BY wid DESC", 0, 1, array(':type' => 'rest')) ->fetchField(); diff --git a/core/modules/dblog/src/Tests/Views/ViewsIntegrationTest.php b/core/modules/dblog/src/Tests/Views/ViewsIntegrationTest.php index 89f7cf05254b..59eb7fc0faca 100644 --- a/core/modules/dblog/src/Tests/Views/ViewsIntegrationTest.php +++ b/core/modules/dblog/src/Tests/Views/ViewsIntegrationTest.php @@ -57,29 +57,31 @@ public function testIntegration() { // Setup a watchdog entry without tokens. $entries[] = array( 'message' => $this->randomMachineName(), - 'variables' => array(), - 'link' => l('Link', 'node/1'), + 'variables' => array('link' => l('Link', 'node/1')), ); // Setup a watchdog entry with one token. $entries[] = array( 'message' => '@token1', - 'variables' => array('@token1' => $this->randomMachineName()), - 'link' => l('Link', 'node/2'), + 'variables' => array('@token1' => $this->randomMachineName(), 'link' => l('Link', 'node/2')), ); // Setup a watchdog entry with two tokens. $entries[] = array( 'message' => '@token1 !token2', - 'variables' => array('@token1' => $this->randomMachineName(), '!token2' => $this->randomMachineName()), // Setup a link with a tag which is filtered by // \Drupal\Component\Utility\Xss::filterAdmin(). - 'link' => l('<object>Link</object>', 'node/2', array('html' => TRUE)), + 'variables' => array( + '@token1' => $this->randomMachineName(), + '!token2' => $this->randomMachineName(), + 'link' => l('<object>Link</object>', 'node/2', array('html' => TRUE)), + ), ); + $logger_factory = $this->container->get('logger.factory'); foreach ($entries as $entry) { $entry += array( 'type' => 'test-views', 'severity' => WATCHDOG_NOTICE, ); - watchdog($entry['type'], $entry['message'], $entry['variables'], $entry['severity'], $entry['link']); + $logger_factory->get($entry['type'])->log($entry['severity'], $entry['message'], $entry['variables']); } $view = Views::getView('test_dblog'); @@ -88,7 +90,7 @@ public function testIntegration() { foreach ($entries as $index => $entry) { $this->assertEqual($view->style_plugin->getField($index, 'message'), String::format($entry['message'], $entry['variables'])); - $this->assertEqual($view->style_plugin->getField($index, 'link'), Xss::filterAdmin($entry['link'])); + $this->assertEqual($view->style_plugin->getField($index, 'link'), Xss::filterAdmin($entry['variables']['link'])); } // Disable replacing variables and check that the tokens aren't replaced. diff --git a/core/modules/locale/src/PoDatabaseWriter.php b/core/modules/locale/src/PoDatabaseWriter.php index 7d2b5fe00ca2..e151ac2f4608 100644 --- a/core/modules/locale/src/PoDatabaseWriter.php +++ b/core/modules/locale/src/PoDatabaseWriter.php @@ -238,7 +238,7 @@ private function importString(PoItem $item) { if (!empty($translation)) { // Skip this string unless it passes a check for dangerous code. if (!locale_string_is_safe($translation)) { - watchdog('locale', 'Import of string "%string" was skipped because of disallowed or malformed HTML.', array('%string' => $translation), WATCHDOG_ERROR); + \Drupal::logger('locale')->error('Import of string "%string" was skipped because of disallowed or malformed HTML.', array('%string' => $translation)); $this->report['skips']++; return 0; } diff --git a/core/modules/migrate/src/MigrateMessage.php b/core/modules/migrate/src/MigrateMessage.php index a9c891664f9e..cc76176c35aa 100644 --- a/core/modules/migrate/src/MigrateMessage.php +++ b/core/modules/migrate/src/MigrateMessage.php @@ -26,7 +26,8 @@ class MigrateMessage implements MigrateMessageInterface { * {@inheritdoc} */ public function display($message, $type = 'status') { - watchdog('migrate', $message, array(), isset($this->map[$type]) ? $this->map[$type] : WATCHDOG_NOTICE); + $type = isset($this->map[$type]) ? $this->map[$type] : WATCHDOG_NOTICE; + \Drupal::logger('migrate')->log($type, $message); } } diff --git a/core/modules/rest/rest.services.yml b/core/modules/rest/rest.services.yml index 6172047a6773..05fac0bfea77 100644 --- a/core/modules/rest/rest.services.yml +++ b/core/modules/rest/rest.services.yml @@ -24,6 +24,11 @@ services: arguments: ['@cache.default', '@entity.manager'] rest.resource_routes: class: Drupal\rest\Routing\ResourceRoutes - arguments: ['@plugin.manager.rest', '@config.factory'] + arguments: ['@plugin.manager.rest', '@config.factory', '@logger.channel.rest'] tags: - { name: 'event_subscriber' } + logger.channel.rest: + class: Drupal\Core\Logger\LoggerChannel + factory_method: get + factory_service: logger.factory + arguments: ['rest'] diff --git a/core/modules/rest/src/Routing/ResourceRoutes.php b/core/modules/rest/src/Routing/ResourceRoutes.php index 56050486dadd..db439dcbce2a 100644 --- a/core/modules/rest/src/Routing/ResourceRoutes.php +++ b/core/modules/rest/src/Routing/ResourceRoutes.php @@ -11,6 +11,7 @@ use Drupal\Core\DependencyInjection\ContainerInjectionInterface; use Drupal\Core\Routing\RouteSubscriberBase; use Drupal\rest\Plugin\Type\ResourcePluginManager; +use Psr\Log\LoggerInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Routing\RouteCollection; @@ -34,6 +35,13 @@ class ResourceRoutes extends RouteSubscriberBase{ */ protected $config; + /** + * A logger instance. + * + * @var \Psr\Log\LoggerInterface + */ + protected $logger; + /** * Constructs a RouteSubscriber object. * @@ -41,10 +49,13 @@ class ResourceRoutes extends RouteSubscriberBase{ * The resource plugin manager. * @param \Drupal\Core\Config\ConfigFactoryInterface $config * The configuration factory holding resource settings. + * @param \Psr\Log\LoggerInterface $logger + * A logger instance. */ - public function __construct(ResourcePluginManager $manager, ConfigFactoryInterface $config) { + public function __construct(ResourcePluginManager $manager, ConfigFactoryInterface $config, LoggerInterface $logger) { $this->manager = $manager; $this->config = $config; + $this->logger = $logger; } /** @@ -70,13 +81,13 @@ protected function alterRoutes(RouteCollection $collection) { // Check that authentication providers are defined. if (empty($enabled_methods[$method]['supported_auth']) || !is_array($enabled_methods[$method]['supported_auth'])) { - watchdog('rest', 'At least one authentication provider must be defined for resource @id', array(':id' => $id), WATCHDOG_ERROR); + $this->logger->error('At least one authentication provider must be defined for resource @id', array(':id' => $id)); continue; } // Check that formats are defined. if (empty($enabled_methods[$method]['supported_formats']) || !is_array($enabled_methods[$method]['supported_formats'])) { - watchdog('rest', 'At least one format must be defined for resource @id', array(':id' => $id), WATCHDOG_ERROR); + $this->logger->error('At least one format must be defined for resource @id', array(':id' => $id)); continue; } diff --git a/core/modules/system/src/Access/CronAccessCheck.php b/core/modules/system/src/Access/CronAccessCheck.php index 7aa9a9d2f514..a5cbb8856059 100644 --- a/core/modules/system/src/Access/CronAccessCheck.php +++ b/core/modules/system/src/Access/CronAccessCheck.php @@ -25,11 +25,11 @@ class CronAccessCheck implements AccessInterface { */ public function access($key) { if ($key != \Drupal::state()->get('system.cron_key')) { - watchdog('cron', 'Cron could not run because an invalid key was used.', array(), WATCHDOG_NOTICE); + \Drupal::logger('cron')->notice('Cron could not run because an invalid key was used.'); return static::KILL; } elseif (\Drupal::state()->get('system.maintenance_mode')) { - watchdog('cron', 'Cron could not run because the site is in maintenance mode.', array(), WATCHDOG_NOTICE); + \Drupal::logger('cron')->notice('Cron could not run because the site is in maintenance mode.'); return static::KILL; } return static::ALLOW; diff --git a/core/modules/system/src/Tests/Pager/PagerTest.php b/core/modules/system/src/Tests/Pager/PagerTest.php index 12295aad2543..b708e296e4bd 100644 --- a/core/modules/system/src/Tests/Pager/PagerTest.php +++ b/core/modules/system/src/Tests/Pager/PagerTest.php @@ -29,8 +29,9 @@ protected function setUp() { parent::setUp(); // Insert 300 log messages. + $logger = $this->container->get('logger.factory')->get('pager_test'); for ($i = 0; $i < 300; $i++) { - watchdog('pager_test', $this->randomString(), array(), WATCHDOG_DEBUG); + $logger->debug($this->randomString()); } $this->admin_user = $this->drupalCreateUser(array( diff --git a/core/modules/views/tests/modules/views_test_data/src/Plugin/views/display/DisplayTest.php b/core/modules/views/tests/modules/views_test_data/src/Plugin/views/display/DisplayTest.php index 4f748839faf6..b14d4093c320 100644 --- a/core/modules/views/tests/modules/views_test_data/src/Plugin/views/display/DisplayTest.php +++ b/core/modules/views/tests/modules/views_test_data/src/Plugin/views/display/DisplayTest.php @@ -96,7 +96,7 @@ public function buildOptionsForm(&$form, FormStateInterface $form_state) { */ public function validateOptionsForm(&$form, FormStateInterface $form_state) { parent::validateOptionsForm($form, $form_state); - watchdog('views', $form_state->getValue('test_option')); + \Drupal::logger('views')->notice($form_state->getValue('test_option')); switch ($form_state['section']) { case 'test_option': if (!trim($form_state->getValue('test_option'))) { diff --git a/core/tests/Drupal/Tests/Core/Controller/ExceptionControllerTest.php b/core/tests/Drupal/Tests/Core/Controller/ExceptionControllerTest.php index 7307780b1acc..3a796ec15609 100644 --- a/core/tests/Drupal/Tests/Core/Controller/ExceptionControllerTest.php +++ b/core/tests/Drupal/Tests/Core/Controller/ExceptionControllerTest.php @@ -29,13 +29,14 @@ public function test405HTML() { $title_resolver = $this->getMock('Drupal\Core\Controller\TitleResolverInterface'); $translation = $this->getMock('Drupal\Core\StringTranslation\TranslationInterface'); $url_generator = $this->getMock('Drupal\Core\Routing\UrlGeneratorInterface'); + $logger_factory = $this->getMock('Drupal\Core\Logger\LoggerChannelFactoryInterface'); $content_negotiation = $this->getMock('Drupal\Core\ContentNegotiation'); $content_negotiation->expects($this->any()) ->method('getContentType') ->will($this->returnValue('html')); - $exception_controller = new ExceptionController($content_negotiation, $title_resolver, $html_page_renderer, $html_fragment_renderer, $translation, $url_generator); + $exception_controller = new ExceptionController($content_negotiation, $title_resolver, $html_page_renderer, $html_fragment_renderer, $translation, $url_generator, $logger_factory); $response = $exception_controller->execute($flat_exception, new Request()); $this->assertEquals($response->getStatusCode(), 405, 'HTTP status of response is correct.'); $this->assertEquals($response->getContent(), 'Method Not Allowed', 'HTTP response body is correct.'); diff --git a/core/tests/Drupal/Tests/Core/Extension/ThemeHandlerTest.php b/core/tests/Drupal/Tests/Core/Extension/ThemeHandlerTest.php index 5daac3f9c915..0627137416da 100644 --- a/core/tests/Drupal/Tests/Core/Extension/ThemeHandlerTest.php +++ b/core/tests/Drupal/Tests/Core/Extension/ThemeHandlerTest.php @@ -110,7 +110,8 @@ protected function setUp() { $this->cssCollectionOptimizer = $this->getMockBuilder('\Drupal\Core\Asset\CssCollectionOptimizer') //\Drupal\Core\Asset\AssetCollectionOptimizerInterface'); ->disableOriginalConstructor() ->getMock(); - $this->themeHandler = new TestThemeHandler($this->configFactory, $this->moduleHandler, $this->state, $this->infoParser, $this->cssCollectionOptimizer, $this->configInstaller, $this->routeBuilder, $this->extensionDiscovery); + $logger = $this->getMock('Psr\Log\LoggerInterface'); + $this->themeHandler = new TestThemeHandler($this->configFactory, $this->moduleHandler, $this->state, $this->infoParser, $logger, $this->cssCollectionOptimizer, $this->configInstaller, $this->routeBuilder, $this->extensionDiscovery); $cache_backend = $this->getMock('Drupal\Core\Cache\CacheBackendInterface'); $this->getContainerWithCacheBins($cache_backend); diff --git a/core/tests/Drupal/Tests/Core/Form/FormBuilderTest.php b/core/tests/Drupal/Tests/Core/Form/FormBuilderTest.php index 0f9e15d7b5b7..977bf91ec3fb 100644 --- a/core/tests/Drupal/Tests/Core/Form/FormBuilderTest.php +++ b/core/tests/Drupal/Tests/Core/Form/FormBuilderTest.php @@ -454,8 +454,4 @@ public static function create(ContainerInterface $container) { function test_form_id_custom_submit(array &$form, FormStateInterface $form_state) { } - // @todo Remove once watchdog() is removed. - if (!defined('WATCHDOG_ERROR')) { - define('WATCHDOG_ERROR', 3); - } } diff --git a/core/tests/Drupal/Tests/Core/Form/FormTestBase.php b/core/tests/Drupal/Tests/Core/Form/FormTestBase.php index 5f038a301ed6..4bc94301bc5d 100644 --- a/core/tests/Drupal/Tests/Core/Form/FormTestBase.php +++ b/core/tests/Drupal/Tests/Core/Form/FormTestBase.php @@ -134,6 +134,11 @@ abstract class FormTestBase extends UnitTestCase { */ protected $httpKernel; + /** + * @var \PHPUnit_Framework_MockObject_MockObject|\Psr\Log\LoggerInterface + */ + protected $logger; + protected function setUp() { $this->moduleHandler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface'); @@ -162,8 +167,9 @@ protected function setUp() { $this->eventDispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'); $this->requestStack = new RequestStack(); $this->requestStack->push($this->request); + $this->logger = $this->getMock('Drupal\Core\Logger\LoggerChannelInterface'); $this->formValidator = $this->getMockBuilder('Drupal\Core\Form\FormValidator') - ->setConstructorArgs(array($this->requestStack, $this->getStringTranslationStub(), $this->csrfToken)) + ->setConstructorArgs(array($this->requestStack, $this->getStringTranslationStub(), $this->csrfToken, $this->logger)) ->setMethods(array('drupalSetMessage')) ->getMock(); $this->formSubmitter = $this->getMockBuilder('Drupal\Core\Form\FormSubmitter') diff --git a/core/tests/Drupal/Tests/Core/Form/FormValidatorTest.php b/core/tests/Drupal/Tests/Core/Form/FormValidatorTest.php index 7c9969905a57..bc6e081962de 100644 --- a/core/tests/Drupal/Tests/Core/Form/FormValidatorTest.php +++ b/core/tests/Drupal/Tests/Core/Form/FormValidatorTest.php @@ -5,7 +5,7 @@ * Contains \Drupal\Tests\Core\Form\FormValidatorTest. */ -namespace Drupal\Tests\Core\Form { +namespace Drupal\Tests\Core\Form; use Drupal\Component\Utility\String; use Drupal\Core\Form\FormState; @@ -92,9 +92,10 @@ public function testValidateInvalidFormToken() { $csrf_token->expects($this->once()) ->method('validate') ->will($this->returnValue(FALSE)); + $logger = $this->getMock('Psr\Log\LoggerInterface'); $form_validator = $this->getMockBuilder('Drupal\Core\Form\FormValidator') - ->setConstructorArgs(array($request_stack, $this->getStringTranslationStub(), $csrf_token)) + ->setConstructorArgs(array($request_stack, $this->getStringTranslationStub(), $csrf_token, $logger)) ->setMethods(array('doValidateForm')) ->getMock(); $form_validator->expects($this->never()) @@ -123,9 +124,10 @@ public function testValidateValidFormToken() { $csrf_token->expects($this->once()) ->method('validate') ->will($this->returnValue(TRUE)); + $logger = $this->getMock('Psr\Log\LoggerInterface'); $form_validator = $this->getMockBuilder('Drupal\Core\Form\FormValidator') - ->setConstructorArgs(array($request_stack, $this->getStringTranslationStub(), $csrf_token)) + ->setConstructorArgs(array($request_stack, $this->getStringTranslationStub(), $csrf_token, $logger)) ->setMethods(array('doValidateForm')) ->getMock(); $form_validator->expects($this->once()) @@ -303,8 +305,10 @@ public function testRequiredErrorMessage($element, $expected_message) { $csrf_token = $this->getMockBuilder('Drupal\Core\Access\CsrfTokenGenerator') ->disableOriginalConstructor() ->getMock(); + $logger = $this->getMock('Psr\Log\LoggerInterface'); + $form_validator = $this->getMockBuilder('Drupal\Core\Form\FormValidator') - ->setConstructorArgs(array(new RequestStack(), $this->getStringTranslationStub(), $csrf_token)) + ->setConstructorArgs(array(new RequestStack(), $this->getStringTranslationStub(), $csrf_token, $logger)) ->setMethods(array('executeValidateHandlers')) ->getMock(); $form_validator->expects($this->once()) @@ -382,15 +386,17 @@ public function testPerformRequiredValidation($element, $expected_message, $call $csrf_token = $this->getMockBuilder('Drupal\Core\Access\CsrfTokenGenerator') ->disableOriginalConstructor() ->getMock(); + $logger = $this->getMock('Psr\Log\LoggerInterface'); + $form_validator = $this->getMockBuilder('Drupal\Core\Form\FormValidator') - ->setConstructorArgs(array(new RequestStack(), $this->getStringTranslationStub(), $csrf_token)) - ->setMethods(array('watchdog')) + ->setConstructorArgs(array(new RequestStack(), $this->getStringTranslationStub(), $csrf_token, $logger)) + ->setMethods(array('setError')) ->getMock(); if ($call_watchdog) { - $form_validator->expects($this->once()) - ->method('watchdog') - ->with('form'); + $logger->expects($this->once()) + ->method('error') + ->with($this->isType('string'), $this->isType('array')); } $form = array(); @@ -478,14 +484,3 @@ public function providerTestPerformRequiredValidation() { } } - -} - -namespace { - if (!defined('WATCHDOG_ERROR')) { - define('WATCHDOG_ERROR', 3); - } - if (!defined('WATCHDOG_NOTICE')) { - define('WATCHDOG_NOTICE', 5); - } -} -- GitLab