3

I have a CakePHP 1.2 application that makes a number of AJAX calls using the AjaxHelper object. The AjaxHelper makes a call to a controller function which then returns some data back to the page.

I would like to log the SQL queries that are executed by the AJAX controller functions. Normally, I would just turn the debug level to 2 in config/core.php, however, this breaks my AJAX functionality because it causes the output SQL queries to be appended to the output that is returned to the client side.

To get around this issue, I would like to be able to log any SQL queries performed to a log file. Any suggestions?

Mansoor Siddiqui
  • 20,853
  • 10
  • 48
  • 67

2 Answers2

5

I found a nice way of adding this logging functionality at this link:

http://cakephp.1045679.n5.nabble.com/Log-SQL-queries-td1281970.html

Basically, in your cake/libs/model/datasources/dbo/ directory, you can make a subclass of the dbo that you're using. For example, if you're using the dbo_mysql.php database driver, then you can make a new class file called dbo_mysql_with_log.php. The file would contain some code along the lines of the following:

App::import('Core', array('Model', 'datasource', 'dbosource', 'dbomysql'));

class DboMysqlWithLog extends DboMysql {
    function _execute($sql) {
        $this->log($sql);
        return parent::_execute($sql);
    }
}

In a nutshell, this class modifies (i.e. overrides) the _execute function of the superclass to log the SQL query before doing whatever logic it normally does.

You can modify your app/config/database.php configuration file to use the new driver that you just created.

RabidFire
  • 6,280
  • 1
  • 28
  • 24
Mansoor Siddiqui
  • 20,853
  • 10
  • 48
  • 67
  • 1
    Just for the record: Using `App::import` is the right way to go about `require`ing the dbo_mysql file. Threw errors for me while running unit tests, but this fixed it. – RabidFire Mar 26 '11 at 09:14
  • anyone know how to do this for cake 2? There is no dbo folder in cake 2. – Joelio Jul 09 '13 at 18:52
  • It's giving "Call to undefined method DboMysqlWithLog::connect()" for me. Any idea what's wrong ? – Vinay Aggarwal Sep 03 '13 at 07:53
  • can you please mention version of cakephp for which this works. – Sumit Kumar Apr 23 '14 at 10:16
  • @Joelio, I found this blog that worked for me for my Cake 2 application - https://ashokg165.wordpress.com/2015/06/23/logging-sql-queries-into-file-in-cakephp-2/ – romellem Jan 05 '17 at 17:49
1

This is a fantastic way to debug things like this, https://github.com/cakephp/debug_kit

David Yell
  • 11,756
  • 13
  • 61
  • 100
  • +1, because DebugKit is awesome. But unfortunately some AJAX calls don't work with DebugKit and so logging to a file can still be helpful. :-) – Simon East Oct 12 '12 at 02:23
  • 2
    debugkit doesnt seem to log sql statements executed in the post of a controller call, only on the rendering controller calls. – Joelio Jul 09 '13 at 18:51