Skip to content

Instantly share code, notes, and snippets.

@edwinheij
Last active February 17, 2017 19:45
Show Gist options
  • Save edwinheij/508fbb749b91612f8f0f to your computer and use it in GitHub Desktop.
Save edwinheij/508fbb749b91612f8f0f to your computer and use it in GitHub Desktop.
Eloquent query logging
<?php
// edit app/config/local/database.php -> 'log' => true
// @ http://stackoverflow.com/questions/19131731/laravel-4-logging-sql-queries
if (Config::get('database.log', false)) {
Event::listen('illuminate.query', function($query, $bindings, $time, $name) {
$data = compact('bindings', 'time', 'name');
// Format binding data for sql insertion
foreach ($bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else if (is_string($binding)) {
$bindings[$i] = "'$binding'";
}
}
// Insert bindings into query
$query = str_replace(array('%', '?'), array('%%', '%s'), $query);
$query = vsprintf($query, $bindings);
$log = new Monolog\Logger('sql');
$log->pushHandler(new Monolog\Handler\StreamHandler(storage_path().'/logs/sql-' . date('Y-m-d') . '.log', Monolog\Logger::INFO));
// add records to the log
$log->addInfo($query, $data);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment