18

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

26
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. – Sukeshini Sep 29 '13 at 10:33
  • @Su123 Yeah...I saw that . It's fixed now – Marius Sep 29 '13 at 10:36
  • 6
    You shouldn't need the print_r here, Magento's logger will autoexpand arrays and objects – Alan Storm Sep 29 '13 at 21:09
  • If you insist on using print_r, a better choice might be to use Zend_Debug::dump($var). – pspahn Sep 30 '13 at 0:10
  • @Alan Storm : Thanks. I tested your suggestion. It works perfectly. – Sukeshini Sep 30 '13 at 12:53
11

Have you tried to do just:

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

Mage log method should expand the array it self.

  • Thanks a lot. It worked. I don't know why it didn't work earlier when I check. – Sukeshini Sep 30 '13 at 3:15
8

As Petar pointed out, it is expanded, so if it is an array or an object, there is no print_r needed. But if you mix it, like:

Mage::log('my string' . $array);

you get a problem, because phps array to string conversion means:

array(... whatever...) -> 'String'

And with an object, php tries to call the __toString method if this doesn't exist, an error is thrown (I think).

And for reference, Mage::log():

\Mage::log
/app/Mage.php:784
public static function log($message, $level = null, $file = '', $forceLog = false)
{
    // ...
    // initialize ... blah stuff...
    // check wether logging is on, developer mode or logging is forced

    try {
        // get the file, define the format... more stuff ... blah ...

        if (is_array($message) || is_object($message)) {
            $message = print_r($message, true);
        }

        $loggers[$file]->log($message, $level);
    }
    catch (Exception $e) {
    }
}

Nothing tested :-)

  • You are correct. I tested the code. If we put like Mage::log('my string' . $array); this will print 'my stringArray' – Sukeshini Sep 30 '13 at 3:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.