//运行命令
php artisan make:listener QueryListener --event=Illuminate\Database\Events\QueryExecuted
//创建的事件文件代码如下:
<?php

namespace App\Listeners;

use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

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

    /**
     * Handle the event.
     *
     * @param  QueryExecuted  $event
     * @return void
     */
    public function handle(QueryExecuted $event)
    {
        //
        $sql = str_replace("?", "'%s'", $event->sql);

        $log = vsprintf($sql, $event->bindings);

        \Log::channel('sqlog')->info($log);
    }
}

在event服务提供者里配置下listen属性:

protected $listen = [
        'App\Events\Event'                         => [
            'App\Listeners\EventListener',
        ],
        //指定sql执行监听
        'Illuminate\Database\Events\QueryExecuted' => [
            'App\Listeners\QueryListener'
        ]
    ];

 

posted on 2018-09-10 13:59  沉默的土豆  阅读(386)  评论(0编辑  收藏  举报