Can laravel log sql queries after all?

时间:2016-08-31 18:27:40

标签: php sql laravel logging query-builder

In Illuminate/Database/Connection.php I can see:

/**
 * 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');
    }
}

Does this data get stored somewhere? How do I enable it globally, if so?

1 个答案:

答案 0 :(得分:2)

I would use middleware to enable it. This would allow you to enable with options (like only in local environments, etc).

You could gather the information with dd() or using Log::info(), etc. Something like:

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());
    }
}