Skip to content

Instantly share code, notes, and snippets.

@digital-drifter
Created July 29, 2018 17:59
Show Gist options
  • Save digital-drifter/1344c52b431e8daf6b1d48b1dacf09c0 to your computer and use it in GitHub Desktop.
Save digital-drifter/1344c52b431e8daf6b1d48b1dacf09c0 to your computer and use it in GitHub Desktop.
Laravel formatted query logging
Event::listen(QueryExecuted::class, function (QueryExecuted $query) {
// Format binding data for sql insertion
foreach ($query->bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$query->bindings[ $i ] = $binding->format('\'Y-m-d H:i:s\'');
} else {
if (is_string($binding)) {
$query->bindings[ $i ] = "'$binding'";
}
}
}
// Insert bindings into query
$boundSql = str_replace(['%', '?'], ['%%', '%s'], $query->sql);
$boundSql = vsprintf($boundSql, $query->bindings);
Log::debug(
"TIME - {$query->time}ms\n" .
" UNBOUND QUERY: {$query->sql};\n" .
" BOUND QUERY: $boundSql;"
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment