php - 尝试在 laravel 5.2 中记录我的查询

标签 php mysql laravel laravel-5

我尝试记录我对 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);
    }
);

我的问题:为什么 Event::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'
     ],
]

关于php - 尝试在 laravel 5.2 中记录我的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36454694/

相关文章:

php - Amazon MarketplaceWebServiceOrders 请求突然失败,PHP curl 给出 SSL CA 证书错误?

php - 页脚中的 float /固定div

php - 在 php preg_match() 中强制使用特殊字符 (@)

mysql - 从 STATION 查询不以元音开头且不以元音结尾的 CITY 名称列表

php - Laravel 进行假迁移

laravel - 将应用程序从宅基地移至Docker

带有CSS问题的PHP随机DIV

c# - 在 C# 中连接到 SQL 数据库

php - 如何在 PHP 和 Mysql 中将字符串值传递给 ajax

php - Laravel 在迁移中给出数据类型 bit/byte