php var_dump($object) or print_r($object) to a log file

前端 未结 4 583
挽巷
挽巷 2021-02-05 16:24

This question is generic, and I would simply like to know how to dump objects to log files. In order to clarify things, i am elaborating through an example.

I have been

相关标签:
4条回答
  • 2021-02-05 16:32

    To be able to use Mage::log(), some conditions need to be met:

    • developer mode must be set to true
    • logging must be activated in the system configuration.

    But, you can also force logging by passing true as 4th param to Mage::log().

    If all conditions are met (or logging is forced), you should find your log file in var/log/shipping.log.

    As a side note: Magento objects tend to be huge and usually contain tons of informations that you usually don't really need for logging/debugging purposes.

    You can reduce the amount of dumped information by using the getData() method, a member of all Magento objects extending Varien_Object:

    Mage::log(print_r($shipment->getData(), true), null, 'shipment.log', true);
    

    You can also dump single attributes by using its proper getter method:

    Mage::log((string) $shipment->getId(), null, 'shipment.log', true);
    

    If you really need full object dumps, I'd recommend to use the debug() method of the object to log the data (this method autodetects recursions which helps avoiding endless loops eating up all memory):

    Mage::log($shipment->debug(), null, 'shipment.log', true);
    

    If you can't get Mage::log() to work, you alternatively could use PHP's core error_log function to log. That's what I sometimes do, if I need just a quick log.

    error_log(print_r($shipment->getData(), true), 3, 'shipment.log');
    
    0 讨论(0)
  • 2021-02-05 16:37

    Perhaps you'd use var_export() function instead, like this:

    var_export($shipment, 1); // to return the string without sending it to STDOUT
    

    Also global functions cannot be called directly within double-quoted string. In your case, Mage::log(var_export($shipment, 1) . '------', null, 'shipments.log') would be ok, I guess. )

    If the object you're trying to dump contains circular references, var_export() will fail, though. Then you can either use var_dump + ob_start/ob_flush combo (there are several examples at the var_dump() doc page), or take an alternate route with serialize() function.

    0 讨论(0)
  • 2021-02-05 16:52

    If you are in Developer Mode you can try if the object supports debug output via $object->debug().

    • http://magebase.com/magento-tutorials/create-your-own-log-files-with-magelog/
    0 讨论(0)
  • 2021-02-05 16:55
    Mage::log(
        $object->debug(), //Objects extending Varien_Object can use this
        Zend_Log::DEBUG,  //Log level
        'my.log',         //Log file name; if blank, will use config value (system.log by default)
        true              //force logging regardless of config setting
    );
    
    0 讨论(0)
提交回复
热议问题