Magento 2: About Messages Logging Mechanism

Magento 2 supports the message logging mechanism via its LoggerInterface class

Posted on September 13, 2017 in Magento2

Magento 2 supports the message logging mechanism via its \Psr\Log\LoggerInterface class. The LoggerInterface class has a preference defined within app/etc/di.xml file for the Magento\Framework\ Logger\Monlolog class type. The main implementation is in the Monolog parent class named Monolog\Logger, which comes from the Monolog vendor.

The LoggerInterface class ueses the following methods to write log to the eight RFC 5424 levels:

  • debug
  • info
  • notice
  • warning
  • error
  • critical
  • alert
  • emergency

To use a logger, we need to pass the LoggerInterface class to a constructor of a class from within we want to use it and then simply make one of the following method calls:


$this->logger->log(\Monolog\Logger::DEBUG, 'debug msg');
$this->logger->log(\Monolog\Logger::INOF, 'info msg');
$this->logger->log(\Monolog\Logger::NOTICE, 'notice msg');
$this->logger->log(\Monolog\Logger::WARNING, 'warning msg');
$this->logger->log(\Monolog\Logger::ERROR, 'error msg');
$this->logger->log(\Monolog\Logger::CRITICAL,  'critical msg');
$this->logger->log(\Monolog\Logger::ALERT, 'alert msg');
$this->logger->log(\Monolog\Logger::EMERGENCY, 'emergency msg');

Alternatively, the preferred shorter version is as follows:


$this->logger->debug('debug msg');
$this->logger->info('info msg');
$this->logger->notice('notice msg');
$this->logger->warning('warning msg');
$this->logger->error('error msg');
$this->logger->critical('critical msg');
$this->logger->alert('alert msg');
$this->logger->emergency('emergency msg');

Both approaches result in the same two log files being created in Magento, which are as follows:

  • var/log/debug.log
  • var/log/system.log

Each of these logger methods can accept an entire array of arbitrary data called context, as follows:


$this->logger->info('User logged in.', ['user'=>'Jeff Yu', 'age'=>'32']);

The proceeding expression will produce the following entry in system.log:


[2017-09-013 09:10:32] main.INFO: User logged in. {"user":"Jeff Yu", "age": 32} []


comments powered by Disqus