Features of application in Magento 2

On the official Magento site you can find a general example of how to use the logger. Unfortunately, the presented example does not reveal all the details and, alas, does not answer the question “how to write logs to your own file”. Therefore, let”s take a closer look at everything.

In the days of Magento 1, probably everyone sooner or later used the Mage :: log method, which was available everywhere in the code and the entry of the simplest log looked like Mage :: log (“ALARM!”, Null, “api.log”). As a result, we had an entry of the following type in the var / log / api.log file
The default format is% timestamp%% priorityName% (% priority%):% message%.
Let”s see how to log data in the simplest case in Magento 2. Most often you will use $ this -> _ logger-> info (“ALARM!”); (if the object has such a property, for example, inherited).
As a result of such a call, we will get the following entry in the var / log / system.log file
Default format: [% datetime%]% channel%.% Level_name%:% message%% context%% extra%If the object does not have such a property (_logger or logger), then we need to first add the \ Psr \ Log \ LoggerInterface dependency to your class and write the resulting object to the $ logger property (according to PSR-2 clause 4.2 and the example presented on the Magento website) …Unlike Magento 1, there are much more nuances here.

1. Parameters for logging.
Consider a general call to a write method

1) Where {level} is, according to PSR-3, 1 of the methods reserved for logging a certain error level (debug, info, notice, warning, error, critical, alert, emerg / emergency).

2) $ message – unlike Magento 1, it must be a string. Those. $ object-> getData () won”t work here. An array with data must be passed to the next parameter. \ Exception objects are an exception, since the \ Magento \ Framework \ Logger \ Monolog implementation handles them separately and automatically passes -> getMessage () further as $ message if the \ Exception object was passed as a message.

3) $ context is an optional parameter, an array.2. The property $ this -> _ logger is not available in all classes.
Featured in: Block, Helper, Model, Collection, etc.Missing in: ResourceModel, Controller, Comand, Setup, etc.It must be said, but in controllers there is a way to get a logger using the ObjectManager (through the $ this -> _ objectManager property). But this is certainly not the most correct way.

Leave a Reply

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