How to print array contents into a log file in magento CE 1.7 without iterating through a loop?
3 Answers
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. Commented Sep 29, 2013 at 10:33
-
-
6You shouldn't need the
print_r
here, Magento's logger will autoexpand arrays and objects Commented Sep 29, 2013 at 21:09 -
If you insist on using
print_r
, a better choice might be to useZend_Debug::dump($var)
.– pspahnCommented Sep 30, 2013 at 0:10 -
@Alan Storm : Thanks. I tested your suggestion. It works perfectly. Commented Sep 30, 2013 at 12:53
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. Commented Sep 30, 2013 at 3:15
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' Commented Sep 30, 2013 at 3:22