Skip to content

Instantly share code, notes, and snippets.

@tiagosampaio
Last active January 11, 2023 23:47
Show Gist options
  • Save tiagosampaio/38ff50540a2a1c343634a3ed7cc15e46 to your computer and use it in GitHub Desktop.
Save tiagosampaio/38ff50540a2a1c343634a3ed7cc15e46 to your computer and use it in GitHub Desktop.
This gist shows how to create custom loggers in Magento 2 in an easy way.

Creating a Custom Logger in Magento 2

We first need to create a virtual type for the custom log handler.

    <virtualType name="MyModule\CustomLogger\Log\Handler" type="Magento\Framework\Logger\Handler\Base">
        <arguments>
            <argument name="fileName" xsi:type="string">/var/log/my_custom_log.log</argument>
        </arguments>
    </virtualType>

Now we create our logger and inject the custom handler in the handlers argument.

    <virtualType name="MyModule\CustomLogger\Logger" type="Magento\Framework\Logger\Monolog">
        <arguments>
            <argument name="handlers" xsi:type="array">
                <item name="my_custom_handler" xsi:type="object">MyModule\CustomLogger\Log\Handler</item>
            </argument>
        </arguments>
    </virtualType>

Now you can inject your custom logger into any class.

    <type name="MyModule\CustomModel\Model">
        <arguments>
            <argument name="logger" xsi:type="object">MyModule\CustomLogger\Logger</argument>
        </arguments>
    </virtualType>

However, the concrete implementation requires an injection of a concrete class, otherwise this implementation might break.

class Model
{
    public function __construct(
        private readonly \Psr\Log\LoggerInterface $logger
    ) {
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment