How to log easily in Magento 2

As a seasoned Magento developer, you might find yourself missing the convenience of Mage::log() from Magento 1. This magical method was a go-to tool for quick debugging. But don’t worry! I’ve discovered a handy alternative for Magento 2 that might just do the trick.

While it’s not an exact replica of our old friend Mage::log(), this solution offers a straightforward way to log debug information in Magento 2. The main difference is that it doesn’t log to a custom file, but it still gets the job done efficiently.

If you’re looking for a one-liner to quickly log debug information, here’s what you can use:

        \Magento\Framework\App\ObjectManager::getInstance()->get(\Psr\Log\LoggerInterface::class)->debug('You Log Here');

You’ll be able to see your log in the var/log/debug.log file.

Of course this is only made to help you debug more easily, do not use the ObjectManager function for maintenance logs. DO NOT USE IS PRODUCTION MODE.

This code snippet allows you to log debug messages with minimal fuss. Simply replace ‘Your Log Message Here’ with whatever information you need to log, and you’re good to go.

While it may not be as concise as Mage::log(), this method provides a quick and easy way to add logging to your Magento 2 projects. It’s particularly useful when you need to quickly debug a function or track down an issue.

If you found a one liner that offers me to log into my custom file, please share it in the comments below !

Happy coding!

Would you like me to explain or break down the code?

Leave a Reply

Your email address will not be published. Required fields are marked *