Laravel 给生产环境添加监听事件 - SQL日志监听

栏目: PHP · 发布时间: 6年前

内容简介:Laravel 给生产环境添加监听事件 - SQL日志监听

laravel版本:5.2.*

一、创建监听器

php artisan make:listener QueryListener --event=Illuminate\\Database\\Events\\QueryExecuted

or

sudo /usr/local/bin/php artisan make:listener QueryListener --event=Illuminate\\Database\\Events\\QueryExecuted

会自动生成文件 app/Listeners/QueryListener.php

二、注册事件

打开 app/Providers/EventServiceProvider.php,在 $listen 中添加 Illuminate\Database\Events\QueryExecuted 事件的监听器为 QueryListener

protected $listen = [  
    'Illuminate\Database\Events\QueryExecuted' => [
        'App\Listeners\QueryListener',
    ],
];

最终代码如下

namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'App\Events\SomeEvent' => [
            'App\Listeners\EventListener',
        ],
        'Illuminate\Database\Events\QueryExecuted' => [
            'App\Listeners\QueryListener',
        ],
    ];
    /**
     * Register any other events for your application.
     *
     * @param  \Illuminate\Contracts\Events\Dispatcher  $events
     * @return void
     */
    public function boot(DispatcherContract $events)
    {
        parent::boot($events);
        //
    }
}

三、添加逻辑

打开 app/Listeners/QueryListener.php

光有一个空的监听器是不够的,我们需要自己实现如何把 $sql 记录到日志中。为此,对 QueryListener 进行改造,完善其 handle 方法如下:

$sql = str_replace("?", "'%s'", $event->sql);
$log = vsprintf($sql, $event->bindings);
Log::info($log);

最终代码如下

namespace App\Listeners;
use Log;
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::info($log);
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Book of CSS3

The Book of CSS3

Peter Gasston / No Starch Press / 2011-5-13 / USD 34.95

CSS3 is the technology behind most of the eye-catching visuals on the Web today, but the official documentation can be dry and hard to follow. Luckily, The Book of CSS3 distills the heady technical la......一起来看看 《The Book of CSS3》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换