tohokuaikiのチラシの裏

技術的ネタとか。

Laravel5でDBのQueryログを出すEvent Listenerを作る

app/(Handlers/)Events/QueryLogTracker.php

雛形は、

$ ./artisan make:event QueryLogTracker

で作る。

<?php

namespace App\Handlers\Events;

use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class QueryLogTracker
{
    /**
     * Create the event handler.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  illuminate.query  $event
     * @return void
     */
    public function handle($query, $bindings, $time, $name)
    {
        Log::debug(sprintf("Query: %s | Bindings: %s",
                           $query,
                           json_encode($bindings)
                           ));
    }
}

app/Providers/EventServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use DB;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'App\Events\SomeEvent' => [
            'App\Listeners\EventListener',
            ],
    ];
    
    
    
    /**
     * @brief 
     * @param 
     * @retval
     */
    public function __construct($app)
    {
        parent::__construct($app);
        
        if (env('APP_DEBUG')){
            $this->listen['illuminate.query'] = [
                'App\Handlers\Events\QueryLogTracker',
                ];
        }
    }

    /**
     * Register any other events for your application.
     *
     * @param  \Illuminate\Contracts\Events\Dispatcher  $events
     * @return void
     */
    public function boot(DispatcherContract $events)
    {
        parent::boot($events);
    }
}