简体   繁体   English

如何在流明 5.7 中记录 api 的所有查询

[英]how log all queries of api in lumen 5.7

I need to see to all queries that executed in api.我需要查看在 api 中执行的所有查询。 I tried 3 ways but none of them work我尝试了 3 种方法,但它们都不起作用

1: 1:

\Illuminate\Support\Facades\DB::listen(function ($query) {
     Log::info($query->sql, ['Bindings' => $query->bindings, 'Time' => $query->time]);
});

listen method is not existed.听方法不存在。

2: 2:

Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
    Log::debug($query->sql . ' - ' . serialize($query->bindings));
});

this one didn't work too.这个也没有用。

3: 3:

DB::connection("mysql2")->enableQueryLog();
DB::connection("mysql2")->getQueryLog();

I put 1 and 2 in bootstrap/app.php and third one in api controller.我将 1 和 2 放在bootstrap/app.php中,第三个放在 api controller 中。

I should mention that i have different databases.我应该提到我有不同的数据库。

Is there other way?还有其他方法吗?

You can try using the 3rd approach in terminable middleware eg:您可以尝试在可终止的中间件中使用第三种方法,例如:

namespace Illuminate\Session\Middleware;

use Closure;

class LogQueries
{
    public function handle($request, Closure $next)
    {
        DB::connection("mysql2")->enableQueryLog();
        return $next($request);
    }

    public function terminate($request, $response)
    {
        Log::info('Queries executed', DB::connection("mysql2")->getQueryLog());
        
    }
}

You can then register this in your app/bootstrap.php as:然后,您可以在您的app/bootstrap.php中将其注册为:

$app->middleware([
   App\Http\Middleware\LogQueries::class
]);

This should enable the query log at the start of the request and then log all queries at the end.这应该在请求开始时启用查询日志,然后在结束时记录所有查询。 The downside is if you perform many large queries (large as in long query string) you will need to keep them in memory until the end of the request which may not be ideal.不利的一面是,如果您执行许多大型查询(如长查询字符串一样大),您需要将它们保存在 memory 中,直到请求结束,这可能并不理想。

Note: I don't fully recall the array structure of the query log so you may need to adjust the log step to work for your needs better.注意:我不完全记得查询日志的数组结构,因此您可能需要调整日志步骤以更好地满足您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM