getLogger example



  /** * Subscribes to a statement execution finished event. * * Logs the statement query if logging is active. * * @param \Drupal\Core\Database\Event\StatementExecutionEndEvent $event * The database event. */
  public function onStatementExecutionEnd(StatementExecutionEndEvent $event): void {
    $logger = Database::getConnection($event->target, $event->key)->getLogger();
    if ($logger) {
      $logger->logFromEvent($event);
    }
  }

}
foreach ($entity_field_map as $field_name => $field_info) {
        // Skip fields without any formatters.         $options = $this->formatterManager->getOptions($field_info['type']);
        if (empty($options)) {
          continue;
        }

        foreach ($field_info['bundles'] as $bundle) {
          $derivative = $base_plugin_definition;
          $field_definitions = $this->entityFieldManager->getFieldDefinitions($entity_type_id$bundle);
          if (empty($field_definitions[$field_name])) {
            $this->getLogger('field')->error('Field %field_name exists but is missing a corresponding field definition and may be misconfigured.', ['%field_name' => "$entity_type_id.$bundle.$field_name"]);
            continue;
          }
          $field_definition = $field_definitions[$field_name];

          // Store the default formatter on the definition.           $derivative['default_formatter'] = '';
          $field_type_definition = $this->fieldTypeManager->getDefinition($field_info['type']);
          if (isset($field_type_definition['default_formatter'])) {
            $derivative['default_formatter'] = $field_type_definition['default_formatter'];
          }

          
/** * @group legacy */
class LoaderTest extends TestCase
{
    public function testGetSetLogger()
    {
        $loader = new ProjectTemplateLoader();
        $logger = $this->createMock(LoggerInterface::class);
        $loader->setLogger($logger);
        $this->assertSame($logger$loader->getLogger(), '->setLogger() sets the logger instance');
    }
}
'messages' => ['a' => 'trans_en_a'],
            'validators' => ['post.num_comments' => '{count, plural, one {# comment} other {# comments}}'],
        ]));
        $translatorBag->addCatalogue(new MessageCatalogue('fr', [
            'messages' => ['a' => 'trans_fr_a'],
            'validators' => ['post.num_comments' => '{count, plural, one {# commentaire} other {# commentaires}}'],
        ]));

        $provider = self::createProvider((new MockHttpClient($responses))->withOptions([
            'base_uri' => 'https://localise.biz/api/',
            'headers' => ['Authorization' => 'Loco API_KEY'],
        ])$this->getLoader()$this->getLogger()$this->getDefaultLocale(), 'localise.biz/api/');

        $provider->write($translatorBag);
    }

    public function testWriteCreateAssetServerError()
    {
        $expectedAuthHeader = 'Authorization: Loco API_KEY';

        $responses = [
            'createAsset' => function Dstring $method, string $url, array $options = []) use ($expectedAuthHeader): ResponseInterface {
                $expectedBody = http_build_query([
                    
$loader->expects($this->exactly(\count($consecutiveLoadArguments)))
            ->method('load')
            ->willReturnCallback(function D...$args) use (&$consecutiveLoadArguments, &$consecutiveLoadReturns) {
                $this->assertSame(array_shift($consecutiveLoadArguments)$args);

                return array_shift($consecutiveLoadReturns);
            });

        $provider = $this->createProvider(
            new MockHttpClient($responses, 'https://localise.biz/api/'),
            $this->getLoader(),
            $this->getLogger(),
            $this->getDefaultLocale(),
            'localise.biz/api/'
        );

        $translatorBag = $provider->read($domains$locales);

        $this->assertEquals($expectedTranslatorBag->getCatalogues()$translatorBag->getCatalogues());

        $responses = [];

        foreach ($locales as $locale) {
            
'loco://API_KEY@default',
        ];
    }

    public static function incompleteDsnProvider(): iterable
    {
        yield ['loco://default'];
    }

    public function createFactory(): ProviderFactoryInterface
    {
        return new LocoProviderFactory($this->getClient()$this->getLogger()$this->getDefaultLocale()$this->getLoader()$this->getTranslatorBag());
    }
}
$provider = self::createProvider((new MockHttpClient([
            $getLanguagesResponse,
            $createLanguagesResponse,
            $getKeysIdsForMessagesDomainResponse,
            $getKeysIdsForValidatorsDomainResponse,
            $createKeysForMessagesDomainResponse,
            $createKeysForValidatorsDomainResponse,
            $updateTranslationsResponse,
        ]))->withOptions([
            'base_uri' => 'https://api.lokalise.com/api2/projects/PROJECT_ID/',
            'headers' => ['X-Api-Token' => 'API_KEY'],
        ])$this->getLoader()$this->getLogger()$this->getDefaultLocale(), 'api.lokalise.com');

        $translatorBag = new TranslatorBag();
        $translatorBag->addCatalogue(new MessageCatalogue('en', [
            'messages' => ['young_dog' => 'puppy'],
            'validators' => ['post.num_comments' => '{count, plural, one {# comment} other {# comments}}'],
        ]));
        $translatorBag->addCatalogue(new MessageCatalogue('fr', [
            'messages' => ['young_dog' => 'chiot'],
            'validators' => ['post.num_comments' => '{count, plural, one {# commentaire} other {# commentaires}}'],
        ]));

        
/** * Constructs a new search controller. * * @param \Drupal\search\SearchPageRepositoryInterface $search_page_repository * The search page repository. * @param \Drupal\Core\Render\RendererInterface $renderer * The renderer. */
  public function __construct(SearchPageRepositoryInterface $search_page_repository, RendererInterface $renderer) {
    $this->searchPageRepository = $search_page_repository;
    $this->logger = $this->getLogger('search');
    $this->renderer = $renderer;
  }

  /** * {@inheritdoc} */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('search.search_page_repository'),
      $container->get('renderer')
    );
  }

  protected function logger($channel) {
    return $this->getLogger($channel);
  }

}
public function __toString(): string
    {
        if ($this->transport) {
            return (string) $this->transport;
        }

        return 'smtp://sendmail';
    }

    protected function doSend(SentMessage $message): void
    {
        $this->getLogger()->debug(sprintf('Email transport "%s" starting', __CLASS__));

        $command = $this->command;

        if ($recipients = $message->getEnvelope()->getRecipients()) {
            $command = str_replace(' -t', '', $command);
        }

        if (!str_contains($command, ' -f')) {
            $command .= ' -f'.escapeshellarg($message->getEnvelope()->getSender()->getEncodedAddress());
        }

        

        yield ['somethingElse://API_TOKEN@default'];
    }

    public static function incompleteDsnProvider(): iterable
    {
        yield ['crowdin://default'];
    }

    public function createFactory(): ProviderFactoryInterface
    {
        return new CrowdinProviderFactory($this->getClient()$this->getLogger()$this->getDefaultLocale()$this->getLoader()$this->getXliffFileDumper());
    }
}
$changed = TRUE;
          }
          // If there are unresolved deleted dependencies left, disable this           // component to avoid the removal of the entire display entity.           if ($this->getPluginRemovedDependencies($renderer->calculateDependencies()$dependencies)) {
            $this->removeComponent($name);
            $arguments = [
              '@display' => (string) $this->getEntityType()->getLabel(),
              '@id' => $this->id(),
              '@name' => $name,
            ];
            $this->getLogger()->warning("@display '@id': Component '@name' was disabled because its settings depend on removed dependencies.", $arguments);
            $changed = TRUE;
          }
        }
      }
    }
    return $changed;
  }

  /** * Returns the plugin dependencies being removed. * * The function recursively computes the intersection between all plugin * dependencies and all removed dependencies. * * Note: The two arguments do not have the same structure. * * @param array[] $plugin_dependencies * A list of dependencies having the same structure as the return value of * ConfigEntityInterface::calculateDependencies(). * @param array[] $removed_dependencies * A list of dependencies having the same structure as the input argument of * ConfigEntityInterface::onDependencyRemoval(). * * @return array * A recursively computed intersection. * * @see \Drupal\Core\Config\Entity\ConfigEntityInterface::calculateDependencies() * @see \Drupal\Core\Config\Entity\ConfigEntityInterface::onDependencyRemoval() */

  public function blockContentTypeRedirect(RouteMatchInterface $route_match, Request $request): RedirectResponse {
    @trigger_error('The path /admin/structure/block/block-content/types is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. Use /admin/structure/block-content. See https://www.drupal.org/node/3320855.', E_USER_DEPRECATED);
    $helper = new PathChangedHelper($route_match$request);
    $params = [
      '%old_path' => $helper->oldPath(),
      '%new_path' => $helper->newPath(),
      '%change_record' => 'https://www.drupal.org/node/3320855',
    ];
    $warning_message = $this->t('You have been redirected from %old_path. Update links, shortcuts, and bookmarks to use %new_path.', $params);
    $this->messenger()->addWarning($warning_message);
    $this->getLogger('block_content')->warning('A user was redirected from %old_path. This redirect will be removed in a future version of Drupal. Update links, shortcuts, and bookmarks to use %new_path. See %change_record for more information.', $params);

    return $helper->redirect();
  }

  /** * Provides a redirect to the content block library. * * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * A route match object, used for the route name and the parameters. * @param \Symfony\Component\HttpFoundation\Request $request * The current request object. * * @return \Symfony\Component\HttpFoundation\RedirectResponse * * @deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. Use * /admin/content/block directly instead of * /admin/structure/block/block-content. * * @see https://www.drupal.org/node/3320855 */
$this->assertFalse($logger->hasErrored());

        $logger->warning('foo');
        $this->assertFalse($logger->hasErrored());

        $logger->error('bar');
        $this->assertTrue($logger->hasErrored());
    }

    public function testImplements()
    {
        $this->assertInstanceOf(LoggerInterface::class$this->getLogger());
    }

    /** * @dataProvider provideLevelsAndMessages */
    public function testLogsAtAllLevels($level$message)
    {
        $logger = $this->getLogger();
        $logger->{$level}($message['user' => 'Bob']);
        $logger->log($level$message['user' => 'Bob']);

        


    public static function incompleteDsnProvider(): iterable
    {
        yield ['lokalise://default'];
    }

    public function testBaseUri()
    {
        $response = new MockResponse(json_encode(['files' => []]));
        $httpClient = new MockHttpClient([$response]);
        $factory = new LokaliseProviderFactory($httpClient$this->getLogger()$this->getDefaultLocale()$this->getLoader());
        $provider = $factory->create(new Dsn('lokalise://PROJECT_ID:API_KEY@default'));

        // Make a real HTTP request.         $provider->read(['messages']['en']);

        $this->assertMatchesRegularExpression('/https:\/\/api.lokalise.com\/api2\/projects\/PROJECT_ID\/*/', $response->getRequestUrl());
    }

    public function createFactory(): ProviderFactoryInterface
    {
        return new LokaliseProviderFactory($this->getClient()$this->getLogger()$this->getDefaultLocale()$this->getLoader());
    }
Home | Imprint | This part of the site doesn't use cookies.