Magento 2 Blog

We like finding ways to make our jobs easier and more productive at Human Element. When a task is seemingly impossible to do without wanting to slam your face into the desk, it’s time to reassess the process. The purpose of this blog is to show the impatient Magento 2 developer (like me) a way to easily log messages to arbitrary log files within the “var/log” directory, similar to how logging worked in Magento 1. Magento 2 supports logging right out of the box via Zend Logging and Monolog, but both options are a pain to use when you just want to quickly log something. With this technique, there is no need to do anything with DI (or your brain) — no DI file updates, no need to mess with constructors, and no need to DI compile — you just log when you want to log. Because while it may often feel easier and more satisfying to fantasize throwing your monitor through a closed window, in the long run, utilizing tricks in M2 are going to keep your day (and career) moving forward in a much more positive way. Check it out:

The Module

  • Create vendor and module directories
    • <magento_docroot>/app/code/HE/Logger
    • All of the following files should be created within this directory.
  • Create registration.php
    • The Code
      • <?php
        \Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        'HE_Logger',
        __DIR__
        );
    • The Code Explained
      • Registers your module.
  • Create etc/module.xml
    • The Code
      • <?xml version="1.0"?>
        <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
        <module name="HE_Logger" setup_version="0.0.1"/></config>
    • The Code Explained
      • Registers your module… again? Silly Magento 2.
  • Create Model/Logger.php
    • The Code
      • <?php
        namespace HE\Logger\Model;
        class Logger
        {
        public static function log($msg, $file, $priority = \Zend\Log\Logger::DEBUG)
        {
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/' . $file);
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->log($priority, $msg);
        }
        }
    • The Code Explained
      • $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/' . $file);
        • Creates a new writer, and specifies the filepath/filename that it will write to, relative to the Magento docroot.
        • e.g. if $file is “myfile.log“, it will write to <magento_docroot>/var/log/myfile.log
      • $logger = new \Zend\Log\Logger();
        • Creates a new logger.
      • $logger->addWriter($writer);
        • Adds the writer to the logger.
      • $logger->log($priority, $msg);
        • Logs our message $msg to our log file, with the priority $priority (which you’ll notice defaults to \Zend\Log\Logger::DEBUG).
        • See “How to use it” for info on how to log with other priorities.
  • Download the complete module

Enable Module

On the command line, from your Magento docroot, run the following commands:

  • php bin/magento module:enable HE_Logger
  • php bin/magento setup:upgrade

How to use it

The following examples all output the same message to the same file, but the priority is different. This, in turn, affects the stamp at the beginning of each logged statement in the log file.

  • Debug (used as the default if you don’t pass the 3rd parameter)
    • \HE\Logger\Model\Logger::log('my message', 'my_log_within_var_log_dir.log');
  • Emergency
    • \HE\Logger\Model\Logger::log('my message', 'my_log_within_var_log_dir.log', \Zend\Log\Logger::EMERG);
  • Alert
    • \HE\Logger\Model\Logger::log('my message', 'my_log_within_var_log_dir.log', \Zend\Log\Logger::ALERT);
  • Critical
    • \HE\Logger\Model\Logger::log('my message', 'my_log_within_var_log_dir.log', \Zend\Log\Logger::CRIT);
  • Error
    • \HE\Logger\Model\Logger::log('my message', 'my_log_within_var_log_dir.log', \Zend\Log\Logger::ERR);
  • Warning
    • \HE\Logger\Model\Logger::log('my message', 'my_log_within_var_log_dir.log', \Zend\Log\Logger::WARN);
  • Notice
    • \HE\Logger\Model\Logger::log('my message', 'my_log_within_var_log_dir.log', \Zend\Log\Logger::NOTICE);
  • Info
    • \HE\Logger\Model\Logger::log('my message', 'my_log_within_var_log_dir.log', \Zend\Log\Logger::INFO);

When to use it

  • When debugging, especially when you can’t use either of the following (which is often the case in staging or production environments)
    • PHP output commands, e.g. “echo“, “var_dump“, “print_r“, etc, or
    • an actual PHP debugger
  • When monitoring code execution, especially when you need to gather information on how it runs over time.
  • When debugging Magento crontabs, which are otherwise difficult to debug.

Where to use it

  • Any Magento modules’ PHP files (your own modules, core modules, or 3rd party modules)
  • .phtml files

And there you have it! One way to keep your sanity and computer in tact when faced with the once tedious task of logging messages in Magento 2! Check out our other blog posts for more M2 help.