DEV Community

Discussion on: Obstacles at the end of the tunnel: trying to finish my tutorial plugin

Collapse
 
ingosteinke profile image
Ingo Steinke, web developer

Logging in Shopware 6 using Logger in a PHP file

I am not sure if this is the official best practice, but at least this works in Shopware 6 for example in a Subscriber.php inside a custom plugin:

  • inject the Logger interface as a service argument
  • receive the service in the constructor function
  • service arguments and constructor paramaters must be in the same order
  • define $this->logger in the constructor,
  • so that you can use $this->logger->info etc. like in a regular Symfony project.

services.xml

<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd">
    <services>
        <service id="MyTheme\Storefront\Subscriber\FooterSubscriber">
            <!-- This must be in the same order as the constructor arguments in FooterSubscriber.php ! -->
            <argument id="logger" type="service" />
            <!-- ... anything else -->
Enter fullscreen mode Exit fullscreen mode

FooterSubscriber.php

use Psr\Log\LoggerInterface;
class FooterSubscriber implements EventSubscriberInterface
{
    /** @var Logger */
    private Logger $logger;
        LoggerInterface $logger
    )
    {
      $this->logger = $logger;
    public function __construct(
Enter fullscreen mode Exit fullscreen mode