coderama coderama - 1 year ago 119
SQL Question

YII: How do you log slow SQL queries?

I only want to log SQL queries that are slow, where slow is determined by any query that takes longer than a value specified by me. Is this possible? And how do I enable it?

DBProfiler works quite nicely, but it seems to always output to the screen and not the file:

array( //db profiler
'countLimit' => 1, // How many times the same query should be executed to be considered inefficient
'slowQueryMin' => 0.1, // Minimum time for the query to be slow

How can I plug into DBProfiler or perhaps in another way so that I can get something written to application.log every time a query is slow?

Answer Source

I ended up writing my own logging function:

private function slowQueryEvaluator($startTime, $endTime, $identifier) {

  $MAX_TIME = 0.1;

  $IP = Controller::getRealIpAddress();
  $userID = -1;
  if (isset(YII::app()->user->id)) {
    $userID = YII::app()->user->id;
  $seconds = $endTime - $startTime;
  if ($seconds > $MAX_TIME ) {
    YII::log($IP.' - '.$userID.' - '.$seconds.' seconds - '.$identifier);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download