Logging is essential for developing and maintaining code. Having good log output helped me countless times to quickly isolate a problem, especially in production settings.

In Shopware, as a Symfony bundle, one could of course use Symfony’s Monolog integration. But Shopware provides a handy wrapper for it, providing an easy way for logging in a standardized way. But this is not mentioned in the documentation, so here comes an intro into logging in Shopware.

Shopware provides a factory for creating a logger class ‘on the fly’. This can be done by registering it in the src/Resources/config/services.xml file of your plugin like this:

<service id="kplngi_custom_logger.custom.logging" class="Monolog\Logger">
    <factory service="Shopware\Core\Framework\Log\LoggerFactory" method="createRotating"/>

The id of the service can be freely chosen, but remember to prefix it with your vendor name, to protect from naming collision. The first argument is used as a prefix for your logs in the var/log folder. The second and third arguments are optional. The former defines how many days of logs will be retained. As you may have noticed, we call createRotating, which creates a rotating log, meaning one log per day, to prevent bloated logs. The latter defines the minimal level for which this logger actually logs messages.

To actually use the logger, inject it into your class as a service argument. When you want to type hint the service, use the \Psr\Log\LoggerInterface, since Monolog implements this interface.