Created
February 11, 2015 14:58
-
-
Save rokde/da05265d61e77da84c13 to your computer and use it in GitHub Desktop.
Logging slow queries in Laravel environments (e.g. /app/start/[environment].php)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @var \Illuminate\Log\Writer $log */ | |
$log = App::make('log'); | |
DB::listen(function ($sql, $bindings, $time) use ($log) { | |
if ( ! starts_with($sql, 'select')) | |
return; | |
// only log long running select statements | |
if ($time <= 1) | |
return; | |
$found = 0; | |
while (($pos = strpos($sql, '?')) !== false) | |
{ | |
$finding = $bindings[$found]; | |
if (is_array($finding)) | |
{ | |
$finding = '"' . implode('", "', $finding) . '"'; | |
} | |
elseif (!is_numeric($finding)) | |
{ | |
$finding = '"' . $finding . '"'; | |
} | |
$sql1 = substr($sql, 0, $pos); | |
$sql2 = substr($sql, $pos + 1); | |
$sql = $sql1 . $finding . $sql2; | |
$found++; | |
} | |
$log->debug($sql . ' | ' . $time . 'ms'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment