Laravel給生產環境添加監聽事件代碼分享

來源:互聯網
上載者:User
本文主要和大家介紹了關於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); }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.