《PHP教程:Laravel給生產環境添加監聽事件(SQL日志監聽)》要點:
本文介紹了PHP教程:Laravel給生產環境添加監聽事件(SQL日志監聽),希望對您有用。如果有疑問,可以聯系我們。
本文主要給大家介紹的是關于Laravel給生產環境添加監聽事件(SQL日志監聽)的相關內容,分享出來供大家參考學習,下面來一起看看詳細的介紹:PHP應用
laravel版本:5.2.*PHP應用
一、創建監聽器PHP應用
php artisan make:listener QueryListener --event=Illuminate\\Database\\Events\\QueryExecuted
orPHP應用
sudo /usr/local/bin/php artisan make:listener QueryListener --event=Illuminate\\Database\\Events\\QueryExecuted
會自動生成文件 app/Listeners/QueryListener.phpPHP應用
二、注冊事件PHP應用
打開 app/Providers/EventServiceProvider.php,在 $listen
中添加 Illuminate\Database\Events\QueryExecuted
事件的監聽器為 QueryListener
PHP應用
protected $listen = [ 'Illuminate\Database\Events\QueryExecuted' => [ 'App\Listeners\QueryListener', ], ];
最終代碼如下PHP應用
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); // } }
三、添加邏輯PHP應用
打開 app/Listeners/QueryListener.phpPHP應用
光有一個空的監聽器是不夠的,我們需要自己實現如何把 $sql
記錄到日志中.為此,對 QueryListener 進行改造,完善其 handle 方法如下:PHP應用
$sql = str_replace("?", "'%s'", $event->sql); $log = vsprintf($sql, $event->bindings); Log::info($log);
最終代碼如下PHP應用
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); } }
總結PHP應用
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對維易PHP的支持.PHP應用
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/607.html