Create A Custom Log File

Create A Custom Log File

A common task for a Magento module developer is to log various outputs such as exceptions, errors or general information during the execution of module. While Magento 2’s Message manager does a good job of showing nicely formatted messages to user but at times, it is not appropriate. For example; when module is running a long process and you need to record a warning or non-critical exception without halting the process or when you need to output large amount of information.


The best way for this situation is to output these to a log file. Magento itself provides system.log file to save normal logs. However, it really helps to create a custom log file which is specific to the module. If there are some issues or errors you can quickly check in a single file without going through Magento’s default logs. It comes really handy during the development.


Let’s see how we can achieve this. We are going to follow these steps:

  1. Create a custom class that will handle logging.

  2. Create a handler. It will take care of log file and will be used in logger class.


Magento 2 uses Monolog for logging purposes. So we will extend this class into our class. Create following file:

Vendor_Name/Module_Name/Logger/MyLogger.php and put following code in this file.

As you can see we have used a Handler class in the constructor, which we will create next.

Create following file:


Vendor_Name/Module_Name/Logger/Handler.php and put following code in this file.

We are all done now. We can use MonoLog\Logger methods for logging, for a comprehensive list of these methods please refer to :


We just need to obtain the object of Vendor_Name\Vendor_Name\Logger\MyLogger class through constructor dependency injection in any class where we need to log.

For example:

That being said, one should use this method with great prejudice as we might end up cluttering up user’s store. A better approach would be to provide user with a backend configuration to enable logs when required so that they can create and send a debug log only when they are facing an issue.


That’s all folks! See you next time. :)



Copyright © 2013-2017 Auriga IT Consulting Pvt Ltd.