Home » Magento, Magento 24 February 2016

Magento 2: Writing Custom Log

In Magento 1, you could simply write your own custom log with the following code:

and it would be saved at MAGENTO_ROOT/var/log/your_log_file.log

However, it’s not that simple and quite different in Magento 2.

As Magento 2 uses dependency injection design pattern, you need to pass the logger instance through the constructor of your custom class. Magento 2 uses Monolog Library for logging purpose. See more at monolog’s Logger class at MAGENTO_ROOT/vendor/monolog/monolog/src/Monolog/Logger.php

In the below code, I am writing custom logs in one of the function of my Block class named ‘YourModule’ (app/code/Chapagain/YourModule/Block/YourModule.php).

As you can see from below code that you can write different types of logs like info, alert, notice, critical, error, debug, etc. The debug log is stored in debug.log file whereas all other logs are stored in system.log file.

The other way is using Object Manager directly. However, this is not encouraged in Magento 2. (http://magento.stackexchange.com/a/75204/1883)

Hope this helps.
Thanks.

Magento 2

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed
  • frostshoxx

    Is there anyway to specify which file we want to log with Monolog?