毕竟可以laravel日志sql查询


Can laravel log sql queries after all?

Illuminate/Database/Connection.php中我可以看到:

/**
 * Indicates whether queries are being logged.
 *
 * @var bool
 */
protected $loggingQueries = false;
/**
 * Enable the query log on the connection.
 *
 * @return void
 */                                                                                                                                              public function enableQueryLog()
{
    $this->loggingQueries = true;
}
/**
 * Disable the query log on the connection.
 *
 * @return void
 */
public function disableQueryLog()
{
    $this->loggingQueries = false;
}
/**
 * Determine whether we're logging queries.
 *
 * @return bool
 */
public function logging()
{
    return $this->loggingQueries;
}
/**
 * Run a SQL statement and log its execution context.
 *
 * @param  string    $query
 * @param  array     $bindings
 * @param  'Closure  $callback
 * @return mixed
 *
 * @throws 'Illuminate'Database'QueryException
 */
protected function run($query, $bindings, Closure $callback)
{
    ...
    $this->logQuery($query, $bindings, $time);
    return $result;
}
/**
 * Log a query in the connection's query log.
 *
 * @param  string  $query
 * @param  array   $bindings
 * @param  float|null  $time
 * @return void                                                                                                                                   */
public function logQuery($query, $bindings, $time = null)                                                                                        {
    ...
    if ($this->loggingQueries) {                                                                                                                         $this->queryLog[] = compact('query', 'bindings', 'time');
    }
}

这些数据是否存储在某个地方?如果是的话,我如何全局启用它?

我会使用中间件来启用它。这将允许您使用选项启用(例如仅在local环境中,等等)。

可以使用dd()Log::info()等来收集信息。比如:

namespace App'Http'Middleware;
use DB;
use Log;
use Closure;
class EnableQueryLogMiddleware
{
    public function handle($request, Closure $next)
    {
        if (env('local')) {
            DB::enableQueryLog();
        }
        return $next($request);
    }
    public function terminate($request, $response)
    {
        // Here you can either Log it, DD, etc.
        dd(DB::getQueryLog());
        Log::info(DB::getQueryLog());
    }
}