Question

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

Was it helpful?

Solution

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.

OTHER TIPS

Have you tried to do just:

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

Mage log method should expand the array it self.

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 :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top