Commit 9be30ef5 authored by alexpott's avatar alexpott

Issue #2271251 by ParisLiakos, undertext, JeroenT, StevenPatz, tim.plunkett:...

Issue #2271251 by ParisLiakos, undertext, JeroenT, StevenPatz, tim.plunkett: Remove usages of watchdog() from non-form and non-controllers.
parent 9830a271
......@@ -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:
......
......@@ -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.
......
......@@ -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.');
}
/**
......
......@@ -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'));
}
}
......
......@@ -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;
}
......
......@@ -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);
}
......
......@@ -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();
......
......@@ -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);
}
}
......@@ -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']
......@@ -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)) {
......
......@@ -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');
}
......
......@@ -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();
......
......@@ -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.
......
......@@ -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;
}
......
......@@ -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);
}
}
......@@ -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']
......@@ -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;
}
......
......@@ -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;
......
......@@ -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(
......
......@@ -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'))) {
......
......@@ -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.');
......
......@@ -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);
......
......@@ -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);
}
}
......@@ -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')
......
......@@ -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');