Shopware 6 Custom Plugin Logger

In this logger guide, you will find the way how to log your custom information in a separate file. Each file will be suffixed by its environment and current date which is already set in the .env file. If you are looking for the following questions then you are in the right place.

  1. How to write in shopware 6 the logging file?
  2. How to debug shopware 6 through logging?
  3. How to write logs in shopware 6 custom plugin ?

 

Step1: Register the built-in LoggerFactory class

Define your new <service> element in <services> of your custom plugin Location: pluginName/Resources/config/services.xml 

<service id="my.custom.logger" class="Monolog\Logger">
    <factory service="Shopware\Core\Framework\Log\LoggerFactory" method="createRotating"/>
        <argument type="string">my-custom-logger</argument>
</service>

Let's discuss the above service attributes and their usage.

  • id: "my.custom.logger" can be any custom name. This id reference will be used in your service as an injection.
  • Argument: It contains the name of the file as a string that will be used prefix for logging.

Step2: Inject logger service in your class

You have already defined a new custom service for the built-in LoggerFactory class. Now it will be used in your customer service class. For example, you have a command class and want to register in service.xml. In this class you need a logger then you can inject a logger reference to it. 

Location: pluginName/Resources/config/services.xml 

<service id="CustomPlugin\Command\MyCustomCommand">
   <tag name="console.command" />
   <argument type="service" id="my.custom.logger"/>
</service>

Step3: Usage of the logger in your class

You have passed the 1 argument of factory logger to your class constructor. You need to define in your constructor as parameter of LoggerInterface

use Psr\Log\LoggerInterface;

class MyCustomCommand extends Command
{
    private LoggerInterface $logger;

    // Logger injection
    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
    
    // Usage of logger in your method 
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->logger->log(Logger::CRITICAL, 'Hello World!');
    }

}

Advertisements