我试图为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);
}
);
我的问题:为什么事件::listen('illuminate.query'不工作?我做错了什么吗?
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'
],
]
将其添加为@Hardy Mathew的答案而不是注释,因为注释不能具有代码格式:
请求的侦听器示例:
<?php
namespace App'Listeners;
use Illuminate'Database'Events'QueryExecuted;
class QueryExecutedListener
{
public function handle(QueryExecuted $event)
{
dd($event);
}
}
请确保按照@Giedrius Kiršys 的指示在EventServiceProvider
中添加侦听器