How to print array contents in log file?

  • How to print array contents into a log file in magento CE 1.7 without iterating through a loop?

  • Marius

    Marius Correct answer

    8 years ago
    Mage::log(print_r($arr, 1), null, 'logfile.log');
    

    Adding a second parameter to print_r will return a string with printed variable.
    [EDIT]
    based on the comments below I feel obligated to offer other options for logging an array.

    Mage::log($arr, null, 'logfile.log');
    

    or if you need a string prefix to the array

    Mage::log('prefix'.Zend_Debug::dump($arr, null, false), null, 'logfile.log');
    

    The second parameter of Zend_Debug::dump() is a label. If this is not null it will be added to before the array dump.
    The third parameter of Zend_Debug::dump() means echo. If it's true then the dump result will be echoed, if it's false it will be returned as a string. In your case you need it to be false.

    Thanks. It worked perfectly. I think you have missed the comma between the parameters of print_r function. Instead there was a full-stop.

    @Su123 Yeah...I saw that . It's fixed now

    You shouldn't need the `print_r` here, Magento's logger will autoexpand arrays and objects

    If you insist on using `print_r`, a better choice might be to use `Zend_Debug::dump($var)`.

    @Alan Storm : Thanks. I tested your suggestion. It works perfectly.

    Great way to debug. `var_dump` make crash magento in many cases. This is perfect to debug all `try-catch` sentences. Thank you so much.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM