source

Larabel 5에서 쿼리를 실행하는 방법DB:: getQueryLog() 빈 어레이 반환

bestscript 2022. 11. 13. 19:36

Larabel 5에서 쿼리를 실행하는 방법DB:: getQueryLog() 빈 어레이 반환

「 」는 「 」로 되어 있습니다.DB::getQueryLog()배열을 .

$user = User::find(5);
print_r(DB::getQueryLog());

결과

Array
(
)

이 쿼리의 로그를 보려면 어떻게 해야 합니까?

기본적으로는 Larabel 5에서는 쿼리 로그가 비활성화되어 있습니다.https://github.com/laravel/framework/commit/e0abfe5c49d225567cb4dfd56df9ef05cc297448

다음을 호출하여 쿼리 로그를 활성화해야 합니다.

DB::enableQueryLog();

// and then you can get query log

dd(DB::getQueryLog());

또는 이벤트 청취자를 등록합니다.

DB::listen(
    function ($sql, $bindings, $time) {
        //  $sql - select * from `ncv_users` where `ncv_users`.`id` = ? limit 1
        //  $bindings - [5]
        //  $time(in milliseconds) - 0.38 
    }
);  

힌트

1. 다중 DB 연결

둘 이상의 DB 연결이 있는 경우 기록할 연결을 지정해야 합니다.

에 대해 쿼리 my_connection:

DB::connection('my_connection')->enableQueryLog();

「 」의 쿼리 하려면 , 「 」를 참조해 주세요.my_connection:

print_r(
   DB::connection('my_connection')->getQueryLog()
);

2. 쿼리 로그를 활성화하는 위치

For an HTTP request lifecycle, you can enable query log in the `handle` method of some `BeforeAnyDbQueryMiddleware` [middleware][1] and then retrieve the executed queries in the [`terminate`][2] method of the same middleware.
class BeforeAnyDbQueryMiddleware
{
    public function handle($request, Closure $next)
    {
        DB::enableQueryLog();
        return $next($request);
    }

    public function terminate($request, $response)
    {
        // Store or dump the log data...
        dd(
            DB::getQueryLog()
        );
    }
}

명령어에서는 CLI 에서는 netable로 로 할 수 .artisan.start이벤트 리스너

를 들면, 「」, 「」에 수 .bootstrap/app.php

$app['events']->listen('artisan.start', function(){
    \DB::enableQueryLog();
});

3. 메모리

Laravel은 모든 쿼리를 메모리에 저장합니다.따라서 많은 행을 삽입하거나 많은 쿼리가 있는 장시간 실행 작업을 수행하는 경우 등 경우에 따라서는 응용 프로그램에서 과도한 메모리를 사용할 수 있습니다.

대부분의 경우 쿼리 로그는 디버깅용으로만 필요하며, 이 경우 개발용으로만 활성화하는 것이 좋습니다.

if (App::environment('local')) {
    // The environment is local
    DB::enableQueryLog();
}

레퍼런스

퀵 디버깅을 위한 실제 쿼리(마지막 1회 실행)에만 관심이 있는 경우:

DB::enableQueryLog();

# your laravel query builder goes here

$laQuery = DB::getQueryLog();

$lcWhatYouWant = $laQuery[0]['query']; # <-------

# optionally disable the query log:
DB::disableQueryLog();

을 추다print_r()$laQuery[0](그것을)$lcWhatYouWant가 의음음음음음음음음음음음음음음음음음음음음으로 .??)

메인 mysql 접속 이외의 것을 사용하고 있는 경우는, 다음의 것을 사용할 필요가 있습니다.

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

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

(접속명 "flash2"는 접속명)

먼저 쿼리 로깅을 활성화해야 합니다.

DB::enableQueryLog();

다음으로 쿼리 로그를 취득할 수 있습니다.

dd(DB::getQueryLog());

BeforeMiddleware에서 실행한 쿼리를 AfterMiddleware에서 가져올 수 있는 쿼리 로깅을 응용 프로그램이 시작되기 전에 활성화하는 것이 좋습니다.

이걸 루트에 올려놔php 파일:

\Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
    echo'<pre>';
    var_dump($query->sql);
    var_dump($query->bindings);
    var_dump($query->time);
    echo'</pre>';
});

msurguy에 의해 송신되어 이 페이지의 소스 코드가 표시됩니다.이 5.2 라라벨의 수정 코드는 코멘트에 기재되어 있습니다.

5에서는 「5.2」의 것 .DB::listen는 단일 파라미터만 수신합니다.

그래서, 만약 당신이 그것을 사용하고 싶다면DB::listenLaravel 5.2에서는 다음과 같은 작업을 수행해야 합니다.

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

사용하다toSql()대신get()다음과 같이 합니다.

$users = User::orderBy('name', 'asc')->toSql();

echo $users;

// Outputs the string:
'select * from `users` order by `name` asc'

larabel 5.8의 경우 dd 또는 dump만 추가하면 됩니다.

예:

DB::table('users')->where('votes', '>', 100)->dd();

또는

DB::table('users')->where('votes', '>', 100)->dump();

레퍼런스: https://laravel.com/docs/5.8/queries#debugging

(Larabel 5.2) 가장 간단한 방법은 sql 쿼리를 감시하기 위해 코드 행을 하나 추가하는 것입니다.

\DB::listen(function($sql) {var_dump($sql); });

쿼리 실행

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

쿼리

StaffRegister::all();

산출량

[2021-03-14 08:00:57] local.DEBUG: query : select * from `staff_registers`  
[2021-03-14 08:00:57] local.DEBUG: time 0.93  
[2021-03-14 08:00:57] local.DEBUG: connection mysql  

완전 구조

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Log;
use App\Models\StaffRegister;

class AuthController extends Controller
{
   public function index(){
   
       \Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
      
           $sql = $query->sql; 
           $time = $query->time;
           $connection = $query->connection->getName();

           Log::debug('query : '.$sql);
           Log::debug('time '.$time);
           Log::debug('connection '.$connection);
       });

       $obj = StaffRegister::all(); 
    
       return $obj;
   }
}

정확한 GET ReposNSE 방법

Larabel 5.2를 사용한 명백한 계속에서 DB:: listen은 하나의 매개 변수만 받습니다...response above : 이 코드를 미들웨어 스크립트에 삽입하여 루트에서 사용할 수 있습니다.

기타:

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$log = new Logger('sql');
$log->pushHandler(new StreamHandler(storage_path().'/logs/sql-' . date('Y-m-d') . '.log', Logger::INFO));

// add records to the log
$log->addInfo($query, $data);

이 코드는 다음과 같습니다.

  • 라라벨 5.2
  • mysql 데이터베이스에 문을 기록합니다.

다음은 @milz의 답변을 바탕으로 한 코드입니다.

    DB::listen(function($sql) {
        $LOG_TABLE_NAME = 'log';
        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);
        if(stripos($query, 'insert into `'.$LOG_TABLE_NAME.'`')===false){
            $toLog = new LogModel();
            $toLog->uId = 100;
            $toLog->sql = $query;
            $toLog->save();
        }
    });

핵심은if(stripos...line: 재귀 방지, 재귀 방지insert into logsql 문을 데이터베이스로 만듭니다.

다음 문의 SQL 쿼리를 인쇄한다고 가정합니다.

$user = User::find(5);

다음과 같이 하면 됩니다.

DB::enableQueryLog();//enable query logging

$user = User::find(5);

print_r(DB::getQueryLog());//print sql query

그러면 Laravel에서 마지막으로 실행된 쿼리가 인쇄됩니다.

답변은 이 기사에 있습니다.https://arjunphp.com/laravel-5-5-log-eloquent-queries/

는 쿼리 로깅을 빠르고 간단하게 실행할 수 있습니다.

이 때, 그 다음에,AppServiceProvider에서bootDB 쿼리를 듣기 위한 콜백 방법:

namespace App\Providers;

use DB;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        DB::listen(function($query) {
            logger()->info($query->sql . print_r($query->bindings, true));
        });
    }
}

도우미 파일에 이 기능을 추가하고 호출만 하면 됩니다.

function getRawQuery($sql){
        $query = str_replace(array('?'), array('\'%s\''), $sql->toSql());
        $query = vsprintf($query, $sql->getBindings());     
        return $query;
}

출력:"select * from user where status = '1' order by id desc limit 25 offset 0"

DB::getQueryLog()만을 사용하는 larabel 5 이후에는 이 기능을 사용할 수 없습니다.디폴트로는 이 값은

 protected $loggingQueries = false;

로 변경하다

protected $loggingQueries = true; 

로그 쿼리를 위해 아래 파일에 있습니다.

/vendor/laravel/framework/src/illuminate/Database/Connection.php 

그런 다음, 이 기능을 사용하여DB::getQueryLog()쿼리를 인쇄할 위치입니다.

언급URL : https://stackoverflow.com/questions/27753868/how-to-get-the-query-executed-in-laravel-5-dbgetquerylog-returning-empty-ar