我尝试记录laravel 5.2的每个SQL查询,所以我找到了很多解决方案,我尝试了下面的代码,但不知怎的,它没有工作,也没有生成日志。
在我的 routes.php - 代码无法正常工作
Event::listen('illuminate.query', function($query, $bindings, $time, $name) {
dd("here");
$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);
echo $query;
Log::info('illuminate.query:'. $query);
});
但我尝试了另一个代码示例并且它工作正常
我的 routes.php中的代码 - 正常工作
DB::enableQueryLog();
DB::listen(
function ($sql) {
// $sql is an object with the properties:
// sql: The query
// bindings: the sql query variables
// time: The execution time for the query
// connectionName: The name of the connection
// To save the executed queries to file:
// Process the sql and the bindings:
foreach ($sql->bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else {
if (is_string($binding)) {
$sql->bindings[$i] = "'$binding'";
}
}
}
// Insert bindings into query
$query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
$query = vsprintf($query, $sql->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);
}
);
我的问题:为什么 事件::听(' illuminate.query' 无效?有什么我做错了吗?
答案 0 :(得分:4)
Laravel不再以illuminate.query
的方式触发事件。它被改为课程。 https://github.com/laravel/framework/commit/41599959d45016f0280d986f758d414fbee81863
现在,如果要记录sql查询,则必须捕获Illuminate\Database\Events\QueryExecuted
事件。
您应该像EventServiceProvider.php
一样定义您的听众:
protected $listen = [
'Illuminate\Database\Events\QueryExecuted' =>[
'App\Listeners\YourListener'
],
]
答案 1 :(得分:2)
将此添加为@Hardy Mathew的答案而非评论,因为评论无法进行代码格式化:
请求的示例监听器:
document.cookie = "cookiename=info123";
alert(document.cookie);
请务必按照@GiedriusKiršys所说的<?php
namespace App\Listeners;
use Illuminate\Database\Events\QueryExecuted;
class QueryExecutedListener
{
public function handle(QueryExecuted $event)
{
dd($event);
}
}
添加听众