CakePHP - get last query run

2019-01-16 11:06发布

I want to get the last query CakePHP ran. I can't turn debug on in core.php and I can't run the code locally. I need a way to get the last sql query and log it to the error log without effecting the live site. This query is failing but is being run.

something like this would be great:

$this->log($this->ModelName->lastQuery);

Thanks in advance.

9条回答
贪生不怕死
2楼-- · 2019-01-16 11:31

Having a quick skim of the book, cakephp api getLog you could turn on logTransaction. Although having not used it, I'm not sure how it will perform.

Otherwise you could experiment with FirePHP and here is the a guide for it,

You might try DebugKit, although off the top of my head I think you do still need debug 2 to get it to work.

Hopefully something might give you a lead. :)

查看更多
干净又极端
3楼-- · 2019-01-16 11:32

You can use this inline.

$dbo = $this->Model->getDatasource();
// store old state
$oldStateFullDebug = $dbo->fullDebug;
// turn fullDebug on
$dbo->fullDebug = true;

// Your code here! eg.
$this->Model->find('all');

// write to logfile
// use print_r with second argument to return a dump of the array
Debugger::log(print_r($dbo->_queriesLog, true));
// restore fullDebug
$dbo->fullDebug = $oldStateFullDebug;
查看更多
beautiful°
4楼-- · 2019-01-16 11:32

This is a very late answer, i know, but for whoever needs this in the future, you can always restrict setting debug to your IP, For example:

Configure::write('debug', 0);
if($_SERVER["REMOTE_ADDR"] == '192.168.0.100'){
Configure::write('debug', 2); //Enables debugging only for your IP.
}
查看更多
狗以群分
5楼-- · 2019-01-16 11:36

Tested in CakePHP v2.3.2

$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);
查看更多
Viruses.
6楼-- · 2019-01-16 11:48

You can use this:

$log = $this->Model->getDataSource()->getLog(false, false);

pr($log);die;
查看更多
虎瘦雄心在
7楼-- · 2019-01-16 11:49

For Cake 2.0, the query log is protected so this will work

function getLastQuery() {
  $dbo = $this->getDatasource();
  $logs = $dbo->getLog();
  $lastLog = end($logs['log']);
  return $lastLog['query'];
}
查看更多
登录 后发表回答