How we can print array variable in log file of Magento 2?

The question:

I am trying to print array variable contents into a log file.

In Magento 1, it was possible using Mage::log(print_r($arr, 1), null, 'logfile.log');

For Magento 2, in class file I have written following code:

protected $_logger;

    public function __construct(PsrLogLoggerInterface $logger) {
        $this->_logger = $logger;
    }


private function getValuesAsHtmlList(MagentoFrameworkObject $object) {
        $options = $this->getOptions($object);
       //$this->_logger->addDebug($options );
        $this->_logger->log(100,null,$options);
    }

When I execute the code after clearing the cache, Debug.log & system.log files are not showing the array contents.

Please share if anyone has any idea about it.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Suppose your array is

$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));

then you have to write below code to write proper array format in your log file

$this->_logger->log(100,print_r($a,true));

It will print in you log file

[2015-11-09 06:58:27] main.DEBUG: Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )

)
 {"is_exception":false} []

Method 2

See declaration of log method

public function  PsrLogLoggerInterface::log($level, $message, array $context = array());

So, you need code like

$this->_logger->log(100, json_encode($options));

Method 3

This method works well for me.

$this->logger->info(print_r($myArray, true));

Then check your system.log file.

Method 4

For array and also object just use

public function __construct(PsrLogLoggerInterface $logger) {
        $this->_logger = $logger;
    }

public function logs(){

$this->logger->info(print_r($orderData, true));
}

and check the output in /var/log/debug.log file

Method 5

protected $_logger;

    public function __construct(PsrLogLoggerInterface $logger) {
        $this->_logger = $logger;
    }

public function logs(){
  $level='log';
$this->_logger->log($level,'errorlog1234', array( array('test1'=>'123', 'test2' => '456'), array('a'=>'b') ));

}

Try This it will print array.
Tested !

Method 6

I see core file uses var_export:

//File: vendor/magento/module-paypal/Model/AbstractIpn.php
/**
 * Log debug data to file
 *
 * @return void
 */
protected function _debug()
{
    if ($this->_config && $this->_config->getValue('debug')) {
        $this->logger->debug(var_export($this->_debugData, true));
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment