Laravel 4 - logging SQL queries

前端 未结 6 1703
时光取名叫无心
时光取名叫无心 2020-11-28 04:40

There are already several questions in regards to logging the SQL query in Laravel 4. But I\'ve tried almost all of them and it\'s still not working the way I want.

6条回答
  •  借酒劲吻你
    2020-11-28 05:31

    While the accepted answer stands correct, this answer explains how to update loic-sharma profiler when making Ajax requests using jQuery. Using this approach one doesn't need to read file logs.

    Step 1

    The first problem is to send the updated profiler data to the client on every Ajax-request. This can be solved using the "after" events of the Laravel application.

    app/filters.php:

    App::after(function($request, $response)
    {
        // If it's a JsonResponse and the profiler is enabled, include it in the response.
        if($response instanceof \Illuminate\Http\JsonResponse && Profiler::isEnabled()) {
    
            $profiler = Profiler::getFacadeRoot();
            $profilerJson = json_encode($profiler->render());
            $content = substr($response->getContent(), 0, -1) . ',"profiler":' . $profilerJson . '}';
            $response->setContent($content);
        }
    });
    

    The App::after filter will run upon every Laravel request. The first line of the closure above, makes sure that it will only continue if a the response is of type JsonResponse and the profiler is enabled. If that is the case, render the profiler and append the HTML to the JSON object.

    Note: this code assumes that the returned JSON is a object. So it will fail for arrays: Response::json(array(1,2,3)).

    Step 2

    Now that the updated profiler HTML is being sent to the client, we must update the DOM with the new profiler HTML using javascript. This should happen every time the client gets a JSON response. jQuery provides global Ajax event handlers, which is perfect to achive this.

    $(document).ajaxSuccess(function(event, request, settings) {
        try {
            json = jQuery.parseJSON(request.responseText);
            if(json.profiler) {
                renderProfiler(json.profiler);
            }
        } catch(error) {
            // Its not JSON.
            return;
        }
    });
    

    Here's a method to replace the old profiler with the new one:

    renderProfiler = function(data) {
        // Remove previous 
        $anbu = $('.anbu');
        $anbu.prev().remove(); // Removes