While debugging Magento 2 extensions, developers often search through different log files. In the case of  payment gateways, the content of these logs are sometimes important for shop owners. To make life easier, we wanted to find a way to manage log entries in a better way so that we can search and find what we need quickly and clients can access effortlessly as well.

At ITEGRATION, our goal was to accomplish this by leveraging Magento 2 and extend the built-in logging system.

We set the following requirements:

  • to be logged in to different places at the same time (file system, database, terminal, slack, nosql…)
  • add useful debugging info to the logs
  • make configuration options accessible to our clients
  • make handlers and log levels manageable in the admin

In Magento 2 we always log-in via the a \Psr\Log\LoggerInterface interface.

Magento 2  implements this interface through the virtual class \Magento\Framework\Logger\Monolog defined in vendor/magento/magento2-base/app/etc/di.xml

Debug and system handlers are defined in the same file

What is a log  handler?

Handlers make it possible to write logs to different channels–like files, database, Slack, etc.

Monolog provides various  pre-defined handlers, which implement logging to Message Queues, browser console, Elasticsearch database, email, New Relic and many more.

How to use log handlers?

Handlers can be easily added to the di.xml of the logging extension.

What are log  processors?

Log processors provide an effective way to add extra data to log entries. Monolog, again, offers some predefined classes to add memory usage, Git status, process ID, environmental variables (e.g. current URL) to the logs.

How to use log  processors?

Just like log handlers, log processors can be defined in the di.xml

By utilizing these features we created an extension that provides clients a user friendly config  section to fine tune various logging options.

A searchable and filterable view of the data stored by the mysql handler is available in the main menu.

Log entries can be flagged in the code, making them filterable. Similarly, they can be linked to a specific entity type.

This approach enabled us to implement a very efficient and flexible logging system, with a number of potential new features, such as two-way  API interface, the option to keep javascript debug logs in a database and integrate further handlers (logstash, browser console, Slack)