Magento 2 – How to Print Array Variable in Log File

logmagento2

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(\Psr\Log\LoggerInterface $logger) {
        $this->_logger = $logger;
    }


private function getValuesAsHtmlList(\Magento\Framework\Object $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.

Best Answer

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} []