Magento 2 Logging
In this tutorial about Magento 2 logging, I show you how to create log messages. One of the main differences for new Magento 2 developers is, that you can’t log messages by a singleton class as you may know from Magento 1. You have to inject your module with a logger class. You can use one pre built one or better: create your own.
Magento 2 Logging
A short and easy way to add logging features to your own module and classes is to inject a already existing logger. For this follow this sample code, which I used in my first Magento 2 import module:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Importer { protected $_logger; public function __construct(\Psr\Log\LoggerInterface $logger) { $this->_logger = $logger; } public function runImport() { $this->_logger->addDebug("call runImport"); } ... } |
With this added to your own model class, a call of runImport() would lead to the following log message:
[2016-12-02 06:42:27] main.DEBUG: call runImport {“is_exception”:false} []
Depending on your needs, you can use one of eight pre defined logging levels. You can do it like:
1 2 3 4 5 6 | $this->_logger->addDebug($message); //log to: var/log/system.log $this->_logger->addInfo($message); //log to: var/log/exception.log $this->_logger->addNotice($message); $this->_logger->addWarning($message); $this->_logger->addError($message); $this->_logger->critical($message); |
PSR-3 Logger
Magento 2 has an implemented PSR-3 Logger module which you can use. It has some advantages, because it is reusable, is based in a standard and uses eight log levels (debug, info, notice, warning, error, critical, alert, emergency). This logging is based on RFC 5424 standard. It is minor important to know. This logger module is based on standard and thought how logging can be improved, so it is a good idea to learn and use it.
Own Logger
If you do not want to use a pre implemented logger, feel free to write your own. You should define log levels, create an appropriate logging module and make it reusable. If you do a good job, feel free to share it with other Magento developers. Personally i think logging depends on own strength and knowledge of each single developer, so if you have no regulations from your department, create your individual module to speed up Magento 2 development.
Conculsion
Logging in Magento 2 is easy. You may use a standardized PHP logger which comes with core Magento 2. Magento 2 has no built in logger, so you can write and use your own. There are no restrictions from this current version of shop system.
Very nice a briefly explained tutorial. Appreciate you for this excellent job. (y)