Modules for Magento

Studying various modules for Magento 2, you can see that logging is used much less frequently compared to Magento 1. This is largely due to the fact that logging has become more difficult. Here I would like to concentrate on the technical side of the issue, namely how to log data, how to write logs to your own file and what is Monolog.


Let”s start with the most important question – What is Monolog and where does it come from. Monolog is a library that implements the PSR-3 standard for data logging. It is Monolog that is used in Magento 2 to write logs.

PSR-3 is, in turn, a standard that describes a general approach for data logging and recommendations for implementing loggers that provide a common interface.

The main points of Monolog to keep in mind are:

Logger is an object that we use to write logs. The logger itself does not record, but manages the handlers. Any number can be created.

Handler is an object that directly processes data. You can add as many handlers as you like to the logger. All of them will be called in turn, regardless of whether this handler was able to handle the error or not. The isHandling method determines whether this handler can handle the received error.

The closest similarity to the handler, from my point of view, is the Event Observer.

Processor is any callable entity. There may be several. They can be assigned both globally and set for the handler. The global processors are started first. The main task of the processor is to add additional data to the log (for example, the IP from which the connection was made, the value of global variables, information on which git branch the code is currently located, and so on).

Formatter – converts the message output before writing. There can be only 1 per handler. It is needed to change the formatting of the message body, for example, to convert text to html or json.

Channel – the name of the logger. It will be written when logging. Since 1 handler can be used in 2 different loggers (it will write logs to 1 and the same file), this will allow us to determine where the error came from.

Level – error level. This parameter for the handler means the minimum error level that will be processed by it.

Bubble – message bubble. After the handler has processed the message, the logger passes the message to the next handler. This process can be stopped using the bubble property. If the handler has the value of this property false (by default, it is always true), then after this handler has completed its work (was able to handle this error), other handlers will no longer be launched.

Sort Order – order of execution. The last added handler is always launched very first. It is this feature that allows you to implement a mechanism for completely disabling the logger (via bubbling false). Handlers added through the constructor go in the order specified in the constructor.

Leave a Reply

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