Logging variables or custom messages to a custom file are usually used in every development of building websites.
In Magento 1, it was common to segment logs into different files (to separate logs for 3rd party extensions etc.). That’s as easy as changing the $file parameter of Mage::log.
But in magento 2 , how we are logging to custom file ? First, we need to dig into default logging way of magento 2.
Magento 2 complies with the PSR-3 standard. As a default implementation of logger it uses Monolog. You will find the default monolog along the path “MAGENTO2_ROOT/vendor/monolog”. The main Magento 2 log facility class is “Magento\Framework\Logger\Monolog, and this is defined in “MAGENTO2_ROOT/app/etc/di.xml” as:

In the first line you can see a preference for LoggerInterface. It means that each time when the code requests a Psr\Log\LoggerInterface interface, an instance of Magento\Framework\Logger\Monolog will be supplied.
As you can see that there is 2 parameters : system and debug in handlers argument :

  • “debug” handler catches the messages with “debug” level and writes them to “/var/log/debug.log” file.
  • “system” handler catches the messages with other levels and writes them either to “/var/log/system.log” file or to “/var/log/exception.log” file in case of exception

Here are some examples of how you can use default logging file in magento 2 :

$this->_logger->addDebug($message); // log location: var/log/system.log
$this->_logger->addInfo($message); // log location: var/log/exception.log
$this->_logger->addNotice($message); // log location: var/log/exception.log
$this->_logger->addError($message); // log location: var/log/exception.log
$this->_logger->critical($e); // log location: var/log/exception.log

Some methods could be used for creating custom log file:

I/Write your own logger extending Monolog with very little effort

Assuming your module is in YourNamespace/YourModule:

1) Write Logger class in Logger/Logger.php:

2) Write Handler class in Logger/Handler.php:


Note: This is the only step which uses Magento code. \Magento\Framework\Logger\Handler\Baseextends Monolog’s StreamHandler and e.g. prepends the $fileName attribute with the Magento base path.

3) Register Logger in Dependency Injection etc/di.xml:


Note: This is not strictly required but allows the DI to pass specific arguments to the constructor. If you do not do this step, then you need to adjust the constructor to set the handler.

4) Use the logger in your Magento classes:

This is done by Dependency Injection. Below you will find a dummy class which only writes a log entry:


II/ You can also write to the logs using the Zend library like below :


You can also print PHP objects and arrays like below :

Happy coding  ! . Hope you’ll find this quick overview of Magento 2 logging and some customization options around it useful.