Last active
March 18, 2016 08:54
-
-
Save ilterocal/b4562380ae2b265bc591 to your computer and use it in GitHub Desktop.
Logging Laravel 5 SQL Queries in Controller.
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
<?php namespace App\Http\Controllers; | |
use Illuminate\Support\Facades\DB; | |
use Illuminate\Http\Request; | |
class QueryLoggingController extends Controller | |
{ | |
public function __construct() | |
{ | |
DB::listen( | |
function ($sql, $bindings, $time) { | |
// To save the executed queries to file: | |
// Process the sql and the bindings: | |
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'), $sql); | |
$query = vsprintf($query, $bindings); | |
// Save the query to file | |
$logFile = fopen( | |
storage_path('logs' . DIRECTORY_SEPARATOR . date('Y-m-d') . '_query.log'), | |
'a+' | |
); | |
fwrite($logFile, date('Y-m-d H:i:s') . ': ' . $query . PHP_EOL); | |
fclose($logFile); | |
} | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment