How to log SQL query of the collection?
-
16-10-2019 - |
Question
I want to log the SQL query for a custom collection. I tried the following code. But did not work. Any suggestions will be appreciated.
Mage::log($collection->getSelect(),null,'test.log',true);
Solution
If you want the SQL query from a collection you need to cast it as string.
Just add (string)
to your previously written logging code.
Mage::log((string)$collection->getSelect(),null,'test.log',true);
OTHER TIPS
Try out $Collection->printLogQuery(true);
this will print collection query.
As Flyingmana explained to me, thanks to him.
$collection->load($printQuery = false, $logQuery = false)
It is important to log or print the query after the loading, because in the beforeLoad
method can lot of thing be done. So the first answer:
Mage::log((string)$collection->getSelect(),null,'test.log',true);
should be used AFTER load
is called.
Step 1:
$result_colletion = print_r($collection->getSelect());
Mage::log($$result_colletion, null, custom_collection.log,true);
Step 2: After that Login into Magento admin section and enable to log setting . Please see below .
System > Configuration > Developer > Log Settings
Step 3: After that see the log file “custom_collection.log” in var/log/ folder .
Mage::log($collection->getSelect()->__toString(), Zend_Log::DEBUG, 'test.log', true);
Edit:
Instead of using null
(fallback to DEBUG
) as second parameter better use one of these from Zend_Log
:
const EMERG = 0; // Emergency: system is unusable
const ALERT = 1; // Alert: action must be taken immediately
const CRIT = 2; // Critical: critical conditions
const ERR = 3; // Error: error conditions
const WARN = 4; // Warning: warning conditions
const NOTICE = 5; // Notice: normal but significant condition
const INFO = 6; // Informational: informational messages
const DEBUG = 7; // Debug: debug messages