CakePHPでMySQLのログを出力する
5 月 18th, 2008 | by admin |/app/models/datasources/dbo/dbo_mysql_log.php
を作成。内容は以下
<?php
uses ('model' . DS . 'datasources' . DS . 'dbo' . DS . 'dbo_mysql');
class DboMysqlLog extends DboMysql {
function showLog($sorted = false) {
if ($sorted) {
$log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC);
} else {
$log = $this->_queriesLog;
}
if ($this->_queriesCnt > 1) {
$text = 'queries';
} else {
$text = 'query';
}
if (LOG_SQL) {
foreach($log as $k => $i) {
$this->log(($k + 1) . ". (affected:{$i['affected']}|rows:{$i['numRows']}) {$i['query']}", LOG_DEBUG);
if ($i['error']) $this->log(" [ERROR] {$i['error']}", LOG_DEBUG);
}
$this->log("{$this->_queriesCnt} {$text} took {$this->_queriesTime} ms", LOG_DEBUG);
//$this->log('', LOG_DEBUG);
//} elseif (php_sapi_name() != 'cli') {
}
if (php_sapi_name() != 'cli') {
print ("<table class=\"cake-sql-log\" id=\"cakeSqlLog_" . preg_replace('/[^A-Za-z0-9_]/', '_', uniqid(time(), true)) . "\" summary=\"Cake SQL Log\" cellspacing=\"0\" border = \"0\">\n<caption>{$this->_queriesCnt} {$text} took {$this->_queriesTime} ms</caption>\n");
print ("<thead>\n<tr><th>Nr</th><th>Query</th><th>Error</th><th>Affected</th><th>Num. rows</th><th>Took (ms)</th></tr>\n</thead>\n<tbody>\n");
foreach ($log as $k => $i) {
print ("<tr><td>" . ($k + 1) . "</td><td>" . h($i['query']) . "</td><td>{$i['error']}</td><td style = \"text-align: right\">{$i['affected']}</td><td style = \"text-align: right\">{$i['numRows']}</td><td style = \"text-align: right\">{$i['took']}</td></tr>\n");
}
print ("</tbody></table>\n");
} else {
foreach ($log as $k => $i) {
print (($k + 1) . ". {$i['query']} {$i['error']}\n");
}
}
}
}
?>
/app/config/core.phpに以下を追加
define('LOG_SQL', true);
で、
/app/tmp/logs/debug.log
にログが出力されます。
https://trac.cakephp.org/ticket/2166
http://openpaste.org/en/6181/
http://www.1×1.jp/blog/2007/04/cakephp_sql_log.html
を参考にさせて頂きました。ありがとうございます。
thank you so much!
コメント by arkantos — 2008 年 6 月 24 日 @ 8:32 AM